Lots of theory - time for some practice!
private final String s1 = new String("1234567890");
private final String s2 = new String("1234567890");
Using plain for loops of 10,000,000, on a warmed-up 64-bit Hotspot, 1.6.0_22 on Intel Mac OS.
eg
@Test public void testConcatenation() {
for (int i = 0; i < COUNT; i++) {
String s3 = s1 + s2;
}
}
With the following statements in the loops
String s3 = s1 + s2;
1.33s
String s3 = new StringBuilder(s1).append(s2).toString();
1.28s
String s3 = new StringBuffer(s1).append(s2).toString();
1.92s
String s3 = s1.concat(s2);
0.70s
String s3 = "1234567890" + "1234567890";
0.0s
So concat is the clear winner, unless you have static strings, in which case the compiler will have taken care of you already.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…