Bottom line: String concat is slower than StringBuffer.append() with 10-20% when using small values and with a factor (10-20-100) when using large values. Of course we are talking about dynamic values , I wouldn't be an idiot to write s = "abc" + "def".
So if you really want to test you should use this code:
Code:
class Test {
public static void main(String args[]) throws Exception {
long start;
String A = "abc";
String B = "def";
String C = "ghi";
start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
String s= "";
// 1
//s = String.valueOf(i)+String.valueOf(i)+String.valueOf(i);
// 2
//s = A+B+C;
// 3
//s += A; s+=B; s+=C;
}
long end = System.currentTimeMillis() - start;
System.out.println("String concat : " +end +" millis");
start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
StringBuffer sb = new StringBuffer(40);
//1
//sb.append(String.valueOf(i));sb.append(String.valueOf(i));sb.append(String.valueOf(i));
//2
//sb.append(A+B+C);
//3
//sb.append(A);sb.append(B);sb.append(C);
sb.toString();
}
end = System.currentTimeMillis() - start;
System.out.println("StringBuffer append : " +end +" millis");
}
}
So if I may say the Test that you made was wrong becouse:
s = "abc"+"def"+"ghi";
is equivalent to
sb.append("abc"+"def"+"ghi");
not at all to
sb.append("abc").append("def").append("ghi");
which is like
s += "abc"; s+="def" ; s+="ghi" (actually another order).
By the way :
it is not fair to put the code
"String s = sb.toString();"
instood of simply sb.toString(); which only acces the method and does not create the object s beside the real result returned by the function.
It's nice to be important but it's more important to be nice.
Thanks for your attitude!