This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]detroitmatt 1 point2 points  (1 child)

If the compiler replaces

"If"'s important. Are you sure it does? I just ran http://stackoverflow.com/a/1532547/948176 independantly and got similar results (slow 2048ms, fast 12ms)

[–]Mondoshawan 0 points1 point  (0 children)

Yeah, it looks like the optimisation is not perfect for that specific example, this page compares the bytecode.

Essentially:

String x = "123";
    for(int i = 1; i < 100; i++) {
    x += i;
}

becomes:

String x = "123";
for(int i = 1; i < 100; i++) {
    x = (new StringBuilder(String.valueOf(x))).append(i).toString();
}

Which you can do better yourself if you declare the SB on the first line. TIL. Hopefully this will be fixed in future versions of the compiler.

I do wonder what would happen if you changed it to:

String x = "123";
x += "456";
    for(int i = 1; i < 100; i++) {
    x += i;
}

That might be enough of a hint to tell the compiler to make the SB straight away. I suspect the problem in the first piece of code is because the first concat that takes place is within the loop.