Java字符串拼接效率測試過程解析
測試代碼:
public class StringJoinTest { public static void main(String[] args) { int count = 10000; long begin, end, time; begin = System.currentTimeMillis(); testString(count); end = System.currentTimeMillis(); time = end - begin; System.out.println('拼接' + count + '次,String消耗時(shí)間:' + time + '毫秒'); begin = System.currentTimeMillis(); testStringBuffer(count); end = System.currentTimeMillis(); time = end - begin; System.out.println('拼接' + count + '次,StringBuffer消耗時(shí)間:' + time + '毫秒'); begin = System.currentTimeMillis(); testStringBuilder(count); end = System.currentTimeMillis(); time = end - begin; System.out.println('拼接' + count + '次,StringBuilder消耗時(shí)間:' + time + '毫秒'); } private static String testStringBuilder(int count) { StringBuilder tem = new StringBuilder(); for (int i = 0; i < count; i++) { tem.append('hello world!'); } return tem.toString(); } private static String testStringBuffer(int count) { StringBuffer tem = new StringBuffer(); for (int i = 0; i < count; i++) { tem.append('hello world!'); } return tem.toString(); } private static String testString(int count) { String tem = ''; for (int i = 0; i < count; i++) { tem += 'hello world!'; } return tem; }}
測試結(jié)果:
結(jié)論:
在少量字符串拼接時(shí)還看不出差別,但隨著數(shù)量的增加,String+拼接效率顯著降低。在達(dá)到100萬次,我本機(jī)電腦已經(jīng)無法執(zhí)行String+拼接了,StringBuilder效率略高于StringBuffer。所以在開發(fā)過程中通常情況下推薦使用StringBuilder。
StringBuffer和StringBuilder的區(qū)別在于StringBuffer是線程安全的。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. jsp實(shí)現(xiàn)局部刷新頁面、異步加載頁面的方法2. ASP基礎(chǔ)入門第二篇(ASP基礎(chǔ)知識)3. ASP中Server.HTMLEncode用法(附自定義函數(shù))4. ASP和PHP文件操作速度的對比5. Spring依賴注入的三種方式實(shí)例詳解6. adodb.recordset.open(rs.open)方法參數(shù)詳解7. JavaServlet的文件上傳和下載實(shí)現(xiàn)方法8. 怎樣打開XML文件?xml文件如何打開?9. jsp實(shí)現(xiàn)簡單用戶7天內(nèi)免登錄10. asp文件如何打開
