java String拼接的方法選擇及效能分析

來源:互聯網
上載者:User

標籤:

 

String 拼接的方法選擇

在拼接靜態字串時,盡量用 +,因為通常編譯器會對此做最佳化,如:

 String test = "this " + "is " + "a " + "test " + "string"

編譯器會把它視為:

 String test = "this is a test string"

在拼接動態字串時,盡量用 StringBuffer 或 StringBuilder的 append,這樣可以減少構造過多的臨時 String 對象。

 

測試代碼:(按照附錄1修改)

 1 public class teststring { 2     3     public void testPlus() { 4         String s = ""; 5         long ts = System.currentTimeMillis(); 6         for (int i = 0; i < 10000; i++) { 7             s = s + String.valueOf(i); 8         } 9         long te = System.currentTimeMillis();10         System.out.println("+ cost {} ms  "+( te - ts));11     }12     13     public void testConcat() {14         String s = "";15         long ts = System.currentTimeMillis();16         for (int i = 0; i < 10000; i++) {17             s = s.concat(String.valueOf(i));18         }19         long te = System.currentTimeMillis();20         System.out.println("concat cost {} ms  "+ (te - ts));21     }22 23     24     public void testStringBuffer() {25         StringBuffer sb = new StringBuffer();26         long ts = System.currentTimeMillis();27         for (int i = 0; i < 10000; i++) {28             sb.append(String.valueOf(i));29         }30         sb.toString();31         long te = System.currentTimeMillis();32         System.out.println("StringBuffer cost {} ms  "+(te - ts));33     }34     35     public void testStringBuilder() {36         StringBuilder sb = new StringBuilder();37         long ts = System.currentTimeMillis();38         for (int i = 0; i < 100000; i++) {39             sb.append(String.valueOf(i));40         }41         sb.toString();42         long te = System.currentTimeMillis();43         System.out.println("StringBuilder cost {} ms  "+(te - ts));44     }45     46     public static void main(String[] args) {47         teststring a = new teststring();48         a.testConcat();49         a.testPlus();50         a.testStringBuffer();51         a.testStringBuilder();52     }53 }

 

運行結果:

concat cost {} ms 113
+ cost {} ms 195
StringBuffer cost {} ms 2
StringBuilder cost {} ms 9

 

附錄:

1 Java 5種字串拼接方式效能比較 http://blog.csdn.net/kimsoft/article/details/3353849

2 Java 效能最佳化之 String 篇  http://www.ibm.com/developerworks/cn/java/j-lo-optmizestring/

java String拼接的方法選擇及效能分析

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.