在Java中使用StringBuilder进行字符串连接通常更可取。情况总是这样吗?

我的意思是:创建一个StringBuilder对象,调用append()方法和最后toString()的开销已经比连接现有的字符串与+操作符两个字符串更小,还是它只适用于更多(两个以上)字符串?

如果有这样一个阈值,它取决于什么(也许是字符串长度,但以哪种方式)?

最后,你是否愿意牺牲+连接的可读性和简便性来换取StringBuilder在较小情况下的性能,比如两个,三个或四个字符串?

在过时的Java优化技巧和Java都市神话中,显式地使用StringBuilder进行常规连接被认为是过时的。


当前回答

对于两个字符串,concat更快,在其他情况下StringBuilder是更好的选择,请参阅我在连接运算符(+)vs concat()中的解释

其他回答

微软认证材料也提出了同样的问题。在. net世界中,StringBuilder对象的开销使得2个String对象的简单连接更加高效。我假设Java字符串也有类似的答案。

The problem with String concatenation is that it leads to copying of the String object with all the associated cost. StringBuilder is not threadsafe and is therefore faster than StringBuffer, which used to be the preferred choice before Java 5. As a rule of thumb, you should not do String concatenation in a loop, which will be called often. I guess doing a few concatenations here and there will not hurt you as long as you are not talking about hundreds and this of course depends on your performance requirements. If you are doing real time stuff, you should be very careful.

一些编译器可能不会用StringBuilder等价物替换任何字符串连接。在依赖编译时优化之前,一定要考虑源代码将使用哪些编译器。

如果你在循环中使用字符串连接,就像这样,

String s = "";
for (int i = 0; i < 100; i++) {
    s += ", " + i;
}

那么你应该使用StringBuilder(不是StringBuffer)而不是String,因为它更快,占用的内存更少。

如果你有一个陈述,

String s = "1, " + "2, " + "3, " + "4, " ...;

那么你可以使用string,因为编译器会自动使用StringBuilder。

看看:http://www.javaspecialists.eu/archive/Issue068.html和http://www.javaspecialists.eu/archive/Issue105.html

在您的环境中进行相同的测试,并检查新的JDK或Java实现是否使用string或StringBuilder更好地执行某种类型的字符串操作。