问题描述
有人告诉我,使用 StringBuffer
连接Java中的字符串比使用 +
运算符更有效率字符串
秒。当你这样做时会发生什么? 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
instance,以及一个新的 String
( out的新值
- String每次迭代都需要
s是不可变的。这非常浪费。用一个 StringBuilder
替换它意味着你只能生成一个 String
而不是用<$ c填充堆$ c>字符串你不关心。
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而不是字符串连接运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!