如果编译器自动将字符串连接转换为StringBuilder,为什么要显式使用StringBuilder? [英] Why use StringBuilder explicitly if the compiler converts string concatenation to a StringBuilder automatically?
问题描述
我很想知道,因为编译器内部使用StringBuilder在执行字符串连接时附加2个字符串,那么问题是什么?如果String连接已经为你完成了工作,我为什么要使用StringBuilder呢?还有其他具体原因吗?
I am wondering, since the compiler internally uses a StringBuilder to append 2 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
而不是简单的字符串连接表达式,例如 a +=+ b
。后者输入更快,更容易阅读,编译器内部仍会使用 StringBuilder
,因此重写它没有性能优势。
As you mention, you should not use StringBuilder
instead 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 StringBuilder
internally anyway so there is no performance advantage by rewriting it.
但是如果在循环中连接大量字符串,则 StringBuilder
非常有用。以下代码效率低下。它需要运行O(n 2 )时间并创建许多临时字符串。
However StringBuilder
is 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.
String result = "";
for (int i = 0; i < foo.length; ++i)
{
result += bar(foo[i]); // Bad
}
请改为尝试:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < foo.length; ++i)
{
sb.append(bar(foo[i]));
}
String result = sb.toString();
编译器只优化简单的 a + b + c
表达式。它无法自动优化上述代码。
The compiler optimises only simple a + b + c
expressions. It cannot optimize the above code automatically.
这篇关于如果编译器自动将字符串连接转换为StringBuilder,为什么要显式使用StringBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!