參考鏈接:https://www.jianshu.com/p/849f1d443b3a
文章結構:
第一部分:對+的原理進行分析
第二部分:+ 和 append 循環對比(貼出代碼,以及分別循環后的反編譯字節碼,來對兩者進行對比)
一: + 底層原理解析(+ 的底層是new StringBuilder 進行append)
1 String str1 = "hello"; 2 String str2 = str1 + " coisini"; 3 System.out.println(str2);
底層,其實在每一次 + 之前 都會new 一個StringBuilder對象,所以效率低,
上述代碼,會被編譯器按照如下順序執行
(使用javap -c 命令查看指令集,參考文章:https://www.cnblogs.com/coisini/p/9779283.html)
具體指令詳解參考上一篇
https://www.cnblogs.com/coisini/p/9789412.html
二: + 和 append 循環對比
1):+ 號循環
1 long start = System.currentTimeMillis(); 2 String str1 = "hello"; 3 for(int i=0; i <10000000; i++){ 4 String str2 = str1 + " coisini"; 5 } 6 long end = System.currentTimeMillis(); 7 System.out.println("開始-結束時間差"+(end-start));
循環次數少,用 + 和append 結果沒差,為了對比結果,所以我循環次數多一點,這里沒考慮堆棧溢出的問題,看,用了2.34秒
看一下反編譯的字節碼
2)append做循環
long start = System.currentTimeMillis(); String str1 = "hello"; StringBuilder builder= new StringBuilder(); for(int i=0; i <10000000; i++){ builder.append("coisni"); } long end = System.currentTimeMillis(); System.out.println("開始-結束時間差"+(end-start));
反編譯字節碼,發現沒,根本沒有新創建對象
總結
1): +的原理,每遇到一個+,就new StringBuilder然后用append
2):性能,字符串拼接少,兩者均可,拼接次數多,用append
生怕自己少截個圖,會給閱讀者,閱讀造成麻煩,所以就啰嗦了點...