问题描述
有人告诉我在 Java 中使用 StringBuffer
来连接字符串比使用 +
运算符来连接 String
的效率更高.当你这样做时,引擎盖下会发生什么?StringBuffer
有何不同?
Someone told me it's more efficient to use StringBuffer
to concatenate strings in Java than to use the +
operator for String
s. What happens under the hood when you do that? What does StringBuffer
do differently?
推荐答案
现在,在几乎所有情况下,最好使用 StringBuilder(它是一个非同步版本;什么时候并行构建字符串?),但会发生以下情况:
It's better to use StringBuilder (it's an unsynchronized version; when do you build strings in parallel?) these days, in almost every case, but here's what happens:
当你对两个字符串使用 + 时,它会编译这样的代码:
When you use + with two strings, it compiles code like this:
String third = first + second;
对于这样的事情:
StringBuilder builder = new StringBuilder( first );
builder.append( second );
third = builder.toString();
因此,对于一些小例子,它通常没有什么区别.但是当你构建一个复杂的字符串时,你通常需要处理的远不止这些;例如,您可能会使用许多不同的附加语句,或者像这样的循环:
Therefore for just little examples, it usually doesn't make a difference. But when you're building a complex string, you've often got a lot more to deal with than this; for example, you might be using many different appending statements, or a loop like this:
for( String str : strings ) {
out += str;
}
在这种情况下,一个新的 StringBuilder
实例和一个新的 String
(out
的新值 - String
s 是不可变的)在每次迭代中都是必需的.这是非常浪费的.用一个 StringBuilder
代替它意味着你可以只生成一个 String
而不用你不关心的 String
填充堆.
In this case, a new StringBuilder
instance, and a new String
(the new value of out
- String
s are immutable) is required in each iteration. This is very wasteful. Replacing this with a single StringBuilder
means you can just produce a single String
and not fill up the heap with String
s you don't care about.
这篇关于为什么在 Java 中使用 StringBuffer 而不是字符串连接运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!