At first step I run this code:
public class Demo {
public static void main(String[] args) {
String x = "x";
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
{
x = x.concat("s");
// x+="k";
}
System.out.println(System.currentTimeMillis() - start);
}
}
Out: 13579.
On second step I run this code:
public class Demo {
public static void main(String[] args) {
String x = "x";
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
{
//x = x.concat("s");
x+="k";
}
System.out.println(System.currentTimeMillis() - start);
}
}
Out: 27328.
And I have two questions:
- Can I say that my banchmark – correct?
- Why so big timeline difference between (+) and concat()??? 13.5 sec VS 27 sec. Why?
I think that your microbenchmark is fine, and I can reproduce your result.
On my JVM, the reason
x += "k"is twice as slow is that under the covers it does the following:StringBuilder;xto theStringBuilder;"k"to theStringBuilder;StringBuilder.toString()and assign the result tox.This copies the character data twice (once in step 2 and once in step 4).
On the other hand,
x = x.concat("s")only copies the data once.This double copying makes
x += "k"two times slower than the other version.If you’re curious, here are the bytecodes that my compiler has generated for the
+=loop:Instructions 21 & 29 are where the two copies are made.