Why to use StringBuffer in Java instead of the str

2019-01-04 23:12发布

Someone told me it's more efficient to use StringBuffer to concatenate strings in Java than to use the + operator for Strings. What happens under the hood when you do that? What does StringBuffer do differently?

18条回答
劳资没心,怎么记你
2楼-- · 2019-01-04 23:44

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;

To something like this:

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;
}

In this case, a new StringBuilder instance, and a new String (the new value of out - Strings 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 Strings you don't care about.

查看更多
Emotional °昔
3楼-- · 2019-01-04 23:44

Further information:

StringBuffer is a thread-safe class


public final class StringBuffer extends AbstractStringBuilder
    implements Serializable, CharSequence
{
// .. skip ..
     public synchronized StringBuffer append(StringBuffer stringbuffer)
    {
        super.append(stringbuffer);
        return this;
    }
// .. skip ..
}

But StringBuilder is not thread-safe, thus it is faster to use StringBuilder if possible


public final class StringBuilder extends AbstractStringBuilder
    implements Serializable, CharSequence
{
// .. skip ..
    public StringBuilder append(String s)
    {
        super.append(s);
        return this;
    }
// .. skip ..
}

查看更多
We Are One
4楼-- · 2019-01-04 23:49

One shouldn't be faster than the other. This wasn't true before Java 1.4.2, because when concatenating more than two strings using the "+" operator, intermediate String objects would be created during the process of building the final string.

However, as the JavaDoc for StringBuffer states, at least since Java 1.4.2 using the "+" operator compiles down to creating a StringBuffer and append()ing the many strings to it. So no difference, apparently.

However, be careful when using adding a string to another inside a loop! For example:

String myString = "";

for (String s : listOfStrings) {
  // Be careful! You're creating one intermediate String object
  // for every iteration on the list (this is costly!)
  myString += s;
}

Keep in mind, however, that usually concatenating a few strings with "+" is cleaner than append()ing them all.

查看更多
Lonely孤独者°
5楼-- · 2019-01-04 23:49

When you concatenate two strings, you actually create a third String object in Java. Using StringBuffer (or StringBuilder in Java 5/6), is faster because it uses an internal array of chars to store the string, and when you use one of its add(...) methods, it doesn't create a new String object. Instead, StringBuffer/Buider appends the internal array.

In simple concatenations, it's not really an issue whether you concatenate strings using StringBuffer/Builder or the '+' operator, but when doing a lot of string concatenations, you'll see that using a StringBuffer/Builder is way faster.

查看更多
Emotional °昔
6楼-- · 2019-01-04 23:49

Because Strings are imutable in Java, every time you concanate a String, new object is created in memory. SpringBuffer use the same object in memory.

查看更多
来,给爷笑一个
7楼-- · 2019-01-04 23:49

The section String Concatenation Operator + of the Java Language Specification gives you some more background information on why the + operator can be so slow.

查看更多
登录 后发表回答