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

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

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

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

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


当前回答

拉尔夫的回答非常棒。我宁愿使用StringBuilder类来构建/装饰String,因为它的用法更像Builder模式。

public String decorateTheString(String orgStr){
            StringBuilder builder = new StringBuilder();
            builder.append(orgStr);
            builder.deleteCharAt(orgStr.length()-1);
            builder.insert(0,builder.hashCode());
            return builder.toString();
}

它可以作为一个助手/构建器来构建字符串,而不是字符串本身。

其他回答

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

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

拉尔夫的回答非常棒。我宁愿使用StringBuilder类来构建/装饰String,因为它的用法更像Builder模式。

public String decorateTheString(String orgStr){
            StringBuilder builder = new StringBuilder();
            builder.append(orgStr);
            builder.deleteCharAt(orgStr.length()-1);
            builder.insert(0,builder.hashCode());
            return builder.toString();
}

它可以作为一个助手/构建器来构建字符串,而不是字符串本身。

一些编译器可能不会用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.

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