java 如果编译器自动将字符串连接转换为 StringBuilder,为什么要显式使用 StringBuilder?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11942368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:01:16  来源:igfitidea点击:

Why use StringBuilder explicitly if the compiler converts string concatenation to a StringBuilder automatically?

javastringbuilder

提问by peter

Possible Duplicate:
StringBuilder vs String concatenation in toString() in Java

可能的重复:
Java 中 toString() 中的 StringBuilder 与字符串连接

I am wondering, since the compiler internally uses a StringBuilder to append Strings when performing String concatenation, then what's the point and why should I bother using StringBuilder if String concatenation already did the job for you? Are there any other specific reasons?

我想知道,由于编译器在执行字符串连接时在内部使用 StringBuilder 来附加字符串,那么有什么意义,如果字符串连接已经为您完成了工作,我为什么还要使用 StringBuilder 呢?还有其他具体原因吗?

回答by Mark Byers

As you mention, you should not use StringBuilderinstead of a simple string concatenation expression such as a + " = " + b. The latter is faster to type, easier to read, and the compiler will use a StringBuilderinternally anyway so there is no performance advantage by rewriting it.

正如您所提到的,您不应该使用StringBuilder代替简单的字符串连接表达式,例如a + " = " + b. 后者键入速度更快,更易于阅读,并且编译器StringBuilder无论如何都会在内部使用 a ,因此重写它没有性能优势。

However StringBuilderis useful if you are concatenating a large number of strings in a loop. The following code is inefficient. It requires O(n2) time to run and creates many temporary strings.

但是StringBuilder,如果您在循环中连接大量字符串,则很有用。以下代码效率低下。它需要 O(n 2) 时间来运行并创建许多临时字符串。

String result = "";
for (int i = 0; i < foo.length; ++i)
{
    result += bar(foo[i]);  // Bad
}

Try this instead:

试试这个:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < foo.length; ++i)
{
    sb.append(bar(foo[i]));
}
String result = sb.toString();

The compiler optimises only simple a + b + cexpressions. It cannot optimize the above code automatically.

编译器只优化简单的a + b + c表达式。它无法自动优化上述代码。

回答by Falmarri

Where are you assuming that string concatination uses stringbuilder internally? Maybe a simple concat gets optimized away, but this will definitely not:

你在哪里假设字符串连接在内部使用 stringbuilder ?也许一个简单的 concat 会被优化掉,但这绝对不会:

String s = "";

for (int i = 0; i < 1000; i++){
  for (int j = 0; j < 1000; j++){
    s+= "" + i + j
}
}