I have a microbenchmark that shows very strange results:
@BenchmarkMode(Mode.Throughput)
@Fork(1)
@State(Scope.Thread)
@Warmup(iterations = 10, time = 1, tim
String concatenation a + b + c
is a very frequent pattern in Java programs, so HotSpot JVM has a special optimization for it: -XX:+OptimizeStringConcat
which is ON by default.
HotSpot JVM recognizes new StringBuilder().append()...append().toString()
pattern in the bytecode and translates it to the optimized machine code without calling actual Java methods and without allocating intermediate objects. I.e. this is a kind of compound JVM intrinsic.
Here is the source code for this optimization.
On the other side, sb.append(); sb.append(); ...
is not handled specially. This sequence is compiled just like a regular Java method calls.
If you rerun the benchmark with -XX:-OptimizeStringConcat
, the performance will be the same for both variants.