本文翻译自:When to use StringBuilder in Java [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
It is supposed to be generally preferable to use a StringBuilder
for string concatenation in Java. 通常最好在Java中使用StringBuilder
进行字符串连接。 Is this always the case? 总是这样吗?
What I mean is this: Is the overhead of creating a StringBuilder
object, calling the append()
method and finally toString()
already smaller then concatenating existing strings with the +
operator for two strings, or is it only advisable for more (than two) strings? 我的意思是这样的:创建一个StringBuilder
对象,调用append()
方法和最后toString()
的开销已经小了,然后用两个字符串的+
运算符连接现有的字符串,或者只建议更多(两个以上) )字符串?
If there is such a threshold, what does it depend on (perhaps the string length, but in which way)? 如果有这样的阈值,它依赖于什么(可能是字符串长度,但以哪种方式)?
And finally, would you trade the readability and conciseness of the +
concatenation for the performance of the StringBuilder
in smaller cases like two, three or four strings? 最后,将您的交易的可读性和简洁+
拼接的性能StringBuilder
在较小的情况下,像二,三或四根弦?
Explicit use of StringBuilder
for regular concatenations is being mentioned as obsolete at obsolete Java optimization tips as well as at Java urban myths . 在过时的Java优化技巧以及Java都市神话中,已经提到明确使用StringBuilder
进行常规连接。
#1楼
参考:https://stackoom.com/question/JUNg/何时在Java中使用StringBuilder-重复
#2楼
对于两个字符串,concat更快,在其他情况下,StringBuilder是更好的选择,请参阅我在串联运算符(+)vs concat()中的解释
#3楼
Some compilers may not replace any string concatenations with StringBuilder equivalents. 某些编译器可能无法用StringBuilder等效替换任何字符串连接。 Be sure to consider which compilers your source will use before relying on compile time optimizations. 在依赖编译时优化之前,请务必考虑源代码将使用哪些编译器。
#4楼
The Microsoft certification material addresses this same question. Microsoft认证材料解决了同样的问题。 In the .NET world, the overhead for the StringBuilder object makes a simple concatenation of 2 String objects more efficient. 在.NET世界中,StringBuilder对象的开销使得2个String对象的简单连接更加高效。 I would assume a similar answer for Java strings. 我会假设Java字符串的类似答案。
#5楼
Have a look at: http://www.javaspecialists.eu/archive/Issue068.html and http://www.javaspecialists.eu/archive/Issue105.html 请查看: http : //www.javaspecialists.eu/archive/Issue068.html和http://www.javaspecialists.eu/archive/Issue105.html
Do the same tests in your environment and check if newer JDK or your Java implementation do some type of string operation better with String
or better with StringBuilder
. 在您的环境中执行相同的测试,并检查较新的JDK或Java实现是否使用String
或使用StringBuilder
更好地执行某种类型的字符串操作。
#6楼
As a general rule, always use the more readable code and only refactor if performance is an issue. 作为一般规则,始终使用更易读的代码,并且只有在性能成为问题时才重构。 In this specific case, most recent JDK's will actually optimize the code into the StringBuilder version in any case. 在这种特定情况下,最新的JDK实际上将在任何情况下将代码优化为StringBuilder版本。
You usually only really need to do it manually if you are doing string concatenation in a loop or in some complex code that the compiler can't easily optimize. 如果您在循环中或在编译器无法轻松优化的某些复杂代码中进行字符串连接,通常只需要手动执行此操作。