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消耗時間:' + time + '毫秒'); begin = System.currentTimeMillis(); testStringBuffer(count); end = System.currentTimeMillis(); time = end - begin; System.out.println('拼接' + count + '次,StringBuffer消耗時間:' + time + '毫秒'); begin = System.currentTimeMillis(); testStringBuilder(count); end = System.currentTimeMillis(); time = end - begin; System.out.println('拼接' + count + '次,StringBuilder消耗時間:' + 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ù)量的增加,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. python如何實(shí)現(xiàn)word批量轉(zhuǎn)HTML2. python excel和yaml文件的讀取封裝3. 利用單元測試對PHP代碼進(jìn)行檢查4. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析5. python3實(shí)現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)6. moment轉(zhuǎn)化時間戳出現(xiàn)Invalid Date的問題及解決7. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個IP代理模塊8. 如何對php程序中的常見漏洞進(jìn)行攻擊9. Python實(shí)現(xiàn)AES加密,解密的兩種方法10. Python實(shí)現(xiàn)http接口自動化測試的示例代碼
