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. Python 的 __str__ 和 __repr__ 方法對比2. IntelliJ IDEA設置默認瀏覽器的方法3. Spring security 自定義過濾器實現Json參數傳遞并兼容表單參數(實例代碼)4. IntelliJ IDEA設置背景圖片的方法步驟5. docker /var/lib/docker/aufs/mnt 目錄清理方法6. Python TestSuite生成測試報告過程解析7. 學python最電腦配置有要求么8. JAMon(Java Application Monitor)備忘記9. Python Scrapy多頁數據爬取實現過程解析10. Python OpenCV去除字母后面的雜線操作
