Java字串拼接效率測試過程解析
阿新 • • 發佈:2020-05-15
測試程式碼:
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是執行緒安全的。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。