本文介绍了for循环中的字符串连接。 Java 9的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我错了,请纠正我。在Java 8中,出于性能原因,当通过+运算符连接多个字符串时,调用了StringBuffer。创建一堆中间字符串对象并污染字符串池的问题已解决。

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 creating a bunch of intermediate string objects and polluting the string pool was "resolved".

Java 9怎么样?
有一个新功能添加为Invokedynamic。还有一个新的类可以更好地解决问题,StringConcatFactory。

What about Java 9?There'a new feature added as Invokedynamic. And a new class that resolves the problem even better, StringConcatFactory.

String result = "";
List<String> list = Arrays.asList("a", "b", "c");
for (String n : list) {
 result+=n;
}

我的问题是:在这个循环中创建了多少个对象?有中介对象吗?我该如何验证?

My question are: How many objects are created in this loop? Are there any intermedier objects? And how can i verify that?

推荐答案

记录中,这是一个 JMH 测试......

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<howmany;++i){
            sb.append(i);
        }
        return sb.toString();
    }

    @Fork(1)
    @Benchmark
    public String concatPlain(){
        String result = "";
        for(int i=0;i<howmany;++i){
            result +=i;
        }
        return result;
    }
}

生成结果(仅适用于这里显示的是100000 ,我没想到:

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

这篇关于for循环中的字符串连接。 Java 9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:40