I just encountered StringBuilder
for the first time and was surprised since Java already has a very powerful String
class that allows appending.
Why a second String
class?
Where can I learn more about StringBuilder
?
I just encountered StringBuilder
for the first time and was surprised since Java already has a very powerful String
class that allows appending.
Why a second String
class?
Where can I learn more about StringBuilder
?
The StringBuilder class is mutable and unlike String, it allows you to modify the contents of the string without needing to create more String objects, which can be a performance gain when you are heavily modifying a string. There is also a counterpart for StringBuilder called StringBuffer which is also synchronized so it is ideal for multithreaded environments.
The biggest problem with String is that any operation you do with it, will always return a new object, say:
Here is a concrete example on why -
As you can see the difference in performance is significant.
String
does not allow appending. Each method you invoke on aString
creates a new object and returns it. This is becauseString
is immutable - it cannot change its internal state.On the other hand
StringBuilder
is mutable. When you callappend(..)
it alters the internal char array, rather than creating a new string object.Thus it is more efficient to have:
rather than
str += i
, which would create 500 new string objects.Note that in the example I use a loop. As helios notes in the comments, the compiler automatically translates expressions like
String d = a + b + c
to something likeNote also that there is
StringBuffer
in addition toStringBuilder
. The difference is that the former has synchronized methods. If you use it as a local variable, useStringBuilder
. If it happens that it's possible for it to be accessed by multiple threads, useStringBuffer
(that's rarer)