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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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:
To something like this:
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:
In this case, a new
StringBuilder
instance, and a newString
(the new value ofout
-String
s are immutable) is required in each iteration. This is very wasteful. Replacing this with a singleStringBuilder
means you can just produce a singleString
and not fill up the heap withString
s you don't care about.Further information:
StringBuffer is a thread-safe class
But StringBuilder is not thread-safe, thus it is faster to use StringBuilder if possible
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
andappend()
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:
Keep in mind, however, that usually concatenating a few strings with "+" is cleaner than
append()
ing them all.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.
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.
The section String Concatenation Operator + of the Java Language Specification gives you some more background information on why the + operator can be so slow.