Method Selection of String concatenation
When stitching a static string, use the + as much as possible, because the compiler usually optimizes it, such as:
String test = "This" + "is" + "a" + "test" + "string"
The compiler will treat it as:
String test = "This is a test string"
When stitching dynamic strings, try to use or, as much as possible StringBuffer
StringBuilder
, to append
reduce the construction of too many temporary string objects.
Test code: (as amended in Appendix 1)
1 Public classteststring {2 3 Public voidTestplus () {4String s = "";5 LongTS =System.currenttimemillis ();6 for(inti = 0; I < 10000; i++) {7s = s +string.valueof (i);8 }9 Longref=System.currenttimemillis ();TenSYSTEM.OUT.PRINTLN ("+ Cost {} MS" + (TE-ts)); One } A - Public voidTestconcat () { -String s = ""; the LongTS =System.currenttimemillis (); - for(inti = 0; I < 10000; i++) { -s =S.concat (string.valueof (i)); - } + LongTe =System.currenttimemillis (); -System.out.println ("concat cost {} MS" + (TE-ts)); + } A at - Public voidTeststringbuffer () { -StringBuffer SB =NewStringBuffer (); - LongTS =System.currenttimemillis (); - for(inti = 0; I < 10000; i++) { - Sb.append (string.valueof (i)); in } - sb.tostring (); to LongTe =System.currenttimemillis (); +System.out.println ("StringBuffer Cost {} MS" + (TE-ts)); - } the * Public voidTeststringbuilder () { $StringBuilder SB =NewStringBuilder ();Panax Notoginseng LongTS =System.currenttimemillis (); - for(inti = 0; I < 100000; i++) { the Sb.append (string.valueof (i)); + } A sb.tostring (); the Longref=System.currenttimemillis (); +System.out.println ("StringBuilder Cost {} MS" + (TE-ts)); - } $ $ Public Static voidMain (string[] args) { -TestString A =Newteststring (); - A.testconcat (); the A.testplus (); - A.teststringbuffer ();Wuyi A.teststringbuilder (); the } -}
Operation Result:
Concat Cost {} MS 113
+ Cost {} MS 195
StringBuffer Cost {} MS 2
StringBuilder Cost {} MS 9
Appendix:
1 Java 5 String Stitching mode performance Comparison http://blog.csdn.net/kimsoft/article/details/3353849
2 Java Performance Optimization String article http://www.ibm.com/developerworks/cn/java/j-lo-optmizestring/
Method selection and performance analysis of Java string splicing