String concatenation in a for loop. Java 9

前端 未结 3 1736
离开以前
离开以前 2020-12-17 16:56

Please correct me if i\'m wrong. In Java 8, for performance reasons, when concatenating several strings by the \"+\" operator StringBuffer was invoked. And the problem of cr

3条回答
  •  忘掉有多难
    2020-12-17 17:54

    For the record, here is a JMH test...

    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.MILLISECONDS)
    @Warmup(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
    @Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
    @State(Scope.Thread)
    public class LoopTest {
    
        public static void main(String[] args) throws RunnerException {
            Options opt = new OptionsBuilder().include(LoopTest.class.getSimpleName())
                    .jvmArgs("-ea", "-Xms10000m", "-Xmx10000m")
                    .shouldFailOnError(true)
                    .build();
            new Runner(opt).run();
        }
    
        @Param(value = {"1000", "10000", "100000"})
        int howmany;
    
        @Fork(1)
        @Benchmark
        public String concatBuilder(){
            StringBuilder sb = new StringBuilder();
            for(int i=0;i

    Produces result (only for 100000 shown here) that I did not really expect:

    LoopTest.concatPlain       100000  avgt    5  3902.711 ± 67.215  ms/op
    LoopTest.concatBuilder     100000  avgt    5     1.850 ±  0.574  ms/op
    

提交回复
热议问题