Why is the StringBuilder chaining pattern sb.append(x).append(y) faster than regular sb.append(x); sb.append(y)?

前端 未结 1 708
北海茫月
北海茫月 2020-12-12 19:19

I have a microbenchmark that shows very strange results:

@BenchmarkMode(Mode.Throughput)
@Fork(1)
@State(Scope.Thread)
@Warmup(iterations = 10, time = 1, tim         


        
相关标签:
1条回答
  • 2020-12-12 19:43

    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.

    0 讨论(0)
提交回复
热议问题