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

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

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

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

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


当前回答

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

其他回答

作为一般规则,总是使用可读性更好的代码,只有在性能有问题时才重构。在这种特定情况下,最新的JDK实际上会在任何情况下将代码优化为StringBuilder版本。

通常只有在循环中进行字符串连接或在编译器无法轻松优化的复杂代码中才需要手动执行。

+运算符在内部使用公共String concat(String str)。此方法复制两个字符串的字符,因此它的内存需求和运行时复杂度与两个字符串的长度成正比。StringBuilder的工作效率更高。

然而,我在这里读到使用+操作符的连接代码在Java 4后编译器上被更改为StringBuilder。所以这可能根本不是问题。(虽然我真的会检查这个语句,如果我在我的代码中依赖它!)

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

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.

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

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

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

如果你有一个陈述,

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

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