给定下面的2个toString()实现,哪个是首选的:

public String toString(){
    return "{a:"+ a + ", b:" + b + ", c: " + c +"}";
}

or

public String toString(){
    StringBuilder sb = new StringBuilder(100);
    return sb.append("{a:").append(a)
          .append(", b:").append(b)
          .append(", c:").append(c)
          .append("}")
          .toString();
}

?

更重要的是,鉴于我们只有3个属性,它可能不会有什么不同,但在什么时候你会从+ concat切换到StringBuilder?


当前回答

在大多数情况下,你不会看到这两种方法之间的实际区别,但很容易构建一个像下面这样的最坏情况:

public class Main
{
    public static void main(String[] args)
    {
        long now = System.currentTimeMillis();
        slow();
        System.out.println("slow elapsed " + (System.currentTimeMillis() - now) + " ms");

        now = System.currentTimeMillis();
        fast();
        System.out.println("fast elapsed " + (System.currentTimeMillis() - now) + " ms");
    }

    private static void fast()
    {
        StringBuilder s = new StringBuilder();
        for(int i=0;i<100000;i++)
            s.append("*");      
    }

    private static void slow()
    {
        String s = "";
        for(int i=0;i<100000;i++)
            s+="*";
    }
}

输出结果为:

slow elapsed 11741 ms
fast elapsed 7 ms

问题是,+=追加到一个字符串重构一个新的字符串,所以它的代价是字符串长度的线性(两者的和)。

对于你的问题

第二种方法更快,但可读性较差,也更难维护。 正如我所说,在你的具体情况下,你可能看不到区别。

其他回答

这取决于字符串的大小。

请看下面的例子:

static final int MAX_ITERATIONS = 50000;
static final int CALC_AVG_EVERY = 10000;

public static void main(String[] args) {
    printBytecodeVersion();
    printJavaVersion();
    case1();//str.concat
    case2();//+=
    case3();//StringBuilder
}

static void case1() {
    System.out.println("[str1.concat(str2)]");
    List<Long> savedTimes = new ArrayList();
    long startTimeAll = System.currentTimeMillis();
    String str = "";
    for (int i = 0; i < MAX_ITERATIONS; i++) {
        long startTime = System.currentTimeMillis();
        str = str.concat(UUID.randomUUID() + "---");
        saveTime(savedTimes, startTime);
    }
    System.out.println("Created string of length:" + str.length() + " in " + (System.currentTimeMillis() - startTimeAll) + " ms");
}

static void case2() {
    System.out.println("[str1+=str2]");
    List<Long> savedTimes = new ArrayList();
    long startTimeAll = System.currentTimeMillis();
    String str = "";
    for (int i = 0; i < MAX_ITERATIONS; i++) {
        long startTime = System.currentTimeMillis();
        str += UUID.randomUUID() + "---";
        saveTime(savedTimes, startTime);
    }
    System.out.println("Created string of length:" + str.length() + " in " + (System.currentTimeMillis() - startTimeAll) + " ms");
}

static void case3() {
    System.out.println("[str1.append(str2)]");
    List<Long> savedTimes = new ArrayList();
    long startTimeAll = System.currentTimeMillis();
    StringBuilder str = new StringBuilder("");
    for (int i = 0; i < MAX_ITERATIONS; i++) {
        long startTime = System.currentTimeMillis();
        str.append(UUID.randomUUID() + "---");
        saveTime(savedTimes, startTime);
    }
    System.out.println("Created string of length:" + str.length() + " in " + (System.currentTimeMillis() - startTimeAll) + " ms");

}

static void saveTime(List<Long> executionTimes, long startTime) {
    executionTimes.add(System.currentTimeMillis() - startTime);
    if (executionTimes.size() % CALC_AVG_EVERY == 0) {
        out.println("average time for " + executionTimes.size() + " concatenations: "
                + NumberFormat.getInstance().format(executionTimes.stream().mapToLong(Long::longValue).average().orElseGet(() -> 0))
                + " ms avg");
        executionTimes.clear();
    }
}

输出:

java bytecode version:8 java.version: 1.8.0_144 [str1.concat(str2)] average time for 10000 concatenations: 0.096 ms avg average time for 10000 concatenations: 0.185 ms avg average time for 10000 concatenations: 0.327 ms avg average time for 10000 concatenations: 0.501 ms avg average time for 10000 concatenations: 0.656 ms avg Created string of length:1950000 in 17745 ms [str1+=str2] average time for 10000 concatenations: 0.21 ms avg average time for 10000 concatenations: 0.652 ms avg average time for 10000 concatenations: 1.129 ms avg average time for 10000 concatenations: 1.727 ms avg average time for 10000 concatenations: 2.302 ms avg Created string of length:1950000 in 60279 ms [str1.append(str2)] average time for 10000 concatenations: 0.002 ms avg average time for 10000 concatenations: 0.002 ms avg average time for 10000 concatenations: 0.002 ms avg average time for 10000 concatenations: 0.002 ms avg average time for 10000 concatenations: 0.002 ms avg Created string of length:1950000 in 100 ms

随着字符串长度的增加,+=和.concat的连接时间也会增加,后者效率更高,但仍然是非常量 这就是绝对需要StringBuilder的地方。

附注:我不认为什么时候在Java中使用StringBuilder是一个真正的复制。 这个问题讨论的是toString(),它在大多数情况下不会执行大字符串的连接。


2019年更新

自java8时代以来,情况发生了一些变化。现在看来(java13), +=的连接时间实际上与str.concat()相同。但是StringBuilder的连接时间仍然是固定的。(上面的原始帖子略有编辑,添加了更多详细的输出)

java bytecode version:13 java.version: 13.0.1 [str1.concat(str2)] average time for 10000 concatenations: 0.047 ms avg average time for 10000 concatenations: 0.1 ms avg average time for 10000 concatenations: 0.17 ms avg average time for 10000 concatenations: 0.255 ms avg average time for 10000 concatenations: 0.336 ms avg Created string of length:1950000 in 9147 ms [str1+=str2] average time for 10000 concatenations: 0.037 ms avg average time for 10000 concatenations: 0.097 ms avg average time for 10000 concatenations: 0.249 ms avg average time for 10000 concatenations: 0.298 ms avg average time for 10000 concatenations: 0.326 ms avg Created string of length:1950000 in 10191 ms [str1.append(str2)] average time for 10000 concatenations: 0.001 ms avg average time for 10000 concatenations: 0.001 ms avg average time for 10000 concatenations: 0.001 ms avg average time for 10000 concatenations: 0.001 ms avg average time for 10000 concatenations: 0.001 ms avg Created string of length:1950000 in 43 ms

值得注意的还有bytecode:8/java。与bytecode:8/java.version:8相比,Version:13组合具有良好的性能优势

在Java 9中,版本1应该更快,因为它被转换为invokedynamic调用。更多细节可以在JEP-280中找到:

其思想是用对java.lang.invoke的简单invokedynamic调用替换整个StringBuilder追加舞蹈。StringConcatFactory,它将接受需要连接的值。

关键在于你是在一个地方写一个连接,还是在一段时间内把它积累起来。

对于您给出的示例,显式使用StringBuilder是没有意义的。(请查看第一个案例的编译代码。)

但是如果你正在构建一个字符串,例如在一个循环中,使用StringBuilder。

为了澄清,假设hugeArray包含数千个字符串,代码如下:

...
String result = "";
for (String s : hugeArray) {
    result = result + s;
}

与以下相比非常浪费时间和内存:

...
StringBuilder sb = new StringBuilder();
for (String s : hugeArray) {
    sb.append(s);
}
String result = sb.toString();

使toString方法尽可能具有可读性!

在我的书中,唯一的例外是,如果你能向我证明它消耗了大量的资源:)(是的,这意味着分析)

还要注意,Java 5编译器生成的代码比早期版本的Java中使用的手写“StringBuffer”方法更快。如果你使用“+”,这和未来的增强是免费的。

我认为这张图对于比较所有使用string的类非常有用: