我有一个基准:
@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 StringConcatTest {
    private int aInt;
    @Setup
    public void prepare() {
        aInt = 100;
    }
    @Benchmark
    public String emptyStringInt() {
        return "" + aInt;
    }
    @Benchmark
    public String valueOfInt() {
        return String.valueOf(aInt);
    }
}下面是结果:
Benchmark                                          Mode  Cnt      Score      Error  Units
StringConcatTest.emptyStringInt                   thrpt   40  66045.741 ± 1306.280  ops/s
StringConcatTest.valueOfInt                       thrpt   40  43947.708 ± 1140.078  ops/s它表明,将空字符串与整数连接在一起比调用String.value(100)快30%。我知道"“+ 100转换为
new StringBuilder().append(100).toString()并应用了-XX:+OptimizeStringConcat优化,使其速度更快。我不明白的是为什么valueOf本身比连接慢。有人能解释一下到底发生了什么吗?为什么"“+ 100更快?OptimizeStringConcat创造了什么魔力?
https://stackoverflow.com/questions/42193955
复制相似问题