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; }}
測試結果:
結論:
在少量字符串拼接時還看不出差別,但隨著數量的增加,String+拼接效率顯著降低。在達到100萬次,我本機電腦已經無法執行String+拼接了,StringBuilder效率略高于StringBuffer。所以在開發過程中通常情況下推薦使用StringBuilder。
StringBuffer和StringBuilder的區別在于StringBuffer是線程安全的。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. ASP中常用的22個FSO文件操作函數整理2. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁3. ASP調用WebService轉化成JSON數據,附json.min.asp4. .Net core 的熱插拔機制的深入探索及卸載問題求救指南5. SharePoint Server 2019新特性介紹6. html清除浮動的6種方法示例7. 讀大數據量的XML文件的讀取問題8. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析9. React+umi+typeScript創建項目的過程10. Vue+elementUI下拉框自定義顏色選擇器方式
