java sb.append,为什么StringBuilder链接模式sb.append(x).append(y)比常规sb.append(x)更快; sb.append(Y)?...

I have a microbenchmark that shows very strange results:

@BenchmarkMode(Mode.Throughput)

@Fork(1)

@State(Scope.Thread)

@Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS, batchSize = 1000)

@Measurement(iterations = 40, time = 1, timeUnit = TimeUnit.SECONDS, batchSize = 1000)

public class Chaining {

private String a1 = "111111111111111111111111";

private String a2 = "222222222222222222222222";

private String a3 = "333333333333333333333333";

@Benchmark

public String typicalChaining() {

return new StringBuilder().append(a1).append(a2).append(a3).toString();

}

@Benchmark

public String noChaining() {

StringBuilder sb = new StringBuilder();

sb.append(a1);

sb.append(a2);

sb.append(a3);

return sb.toString();

}

}

I'm expecting the results of both tests to be the same or at least very close. However, the difference is almost 5x:

# Run complete. Total time: 00:01:41

Benchmark Mode Cnt Score Error Units

Chaining.noChaining thrpt 40 8538.236 ± 209.924 ops/s

Chaining.typicalChaining thrpt 40 36729.523 ± 988.936 ops/s

Does anybody know how that is possible?

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值