It used to be the case that some Java bytecode compilers would compile the String concatenation operator (+
) to operations on a temporary StringBuilder
.
However:
- This was an implementation detail. Though the JLS (in some versions1) said that it may be optimized in that way, it was never stated that it shall be.
- This is not how more recent OpenJDK Java compilers deal with this. Concatenation expressions are now compiled by the bytecode compiler to
invokedynamic
calls ... which are then optimized by the JIT compiler.
However, your example involves concatenation in a loop. I don't think that JIT compiler in current versions of Java can optimize across multiple loop iterations.
But, that may change too. Indeed, JEP 280 hints that the "indifying" of string concatenations by the bytecode compiler will enable further JIT compiler optimization. That could include optimization of loops like the 2nd version of your example. And if it does change, "hand optimization" to use StringBuilder
calls in your source code could actually interfere with the JIT compiler's ability to optimize.
My advice: avoid premature / unnecessary optimization. Unless your application-level profiling tells you that a particular concatenation sequence is a significant bottleneck, leave it alone.
1 - For example, the Java 18 JLS says: "An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." JLS 15.18.1.