2 ms·
The JVM does rewrite individual concatenations as StringBuilders (so a+b+c+d results in one StringBuilder with three .append() operations), but the real perform
by m_myers 15y ago
The JVM does rewrite individual concatenations as StringBuilders (so a+b+c+d results in one StringBuilder with three .append() operations), but the real performance problem is concatenating in a loop.
String result = "";
for (String str : myStrings) {
result += str + " "; // on each execution, a new StringBuilder is created
}
as opposed to
StringBuilder result = new StringBuilder();
for (String str : myStrings) {
result.append(str).append(" ");
}
The JVM can't hoist the generated StringBuilder out of loops to produce the second, faster piece of code. I believe the CLR is the same.
- njw45 15y agoLater JVMs do escape analysis, though - so there's not necessarily any difference between the two methods...
- m_myers 15y agoAt least in Oracle Java 1.6 update 24, which is supposed to have escape analysis enabled by default, it is a huge difference. I don't know if Java 7's analysis is smarter.