I have read in a Java book that says:
Because a
Stringis immutable, usingStringBufferis more efficient.
I understand that String instances are immutable.
I also understand that StringBuffer makes processing Strings more effcient than normal.
But the thing I can't work out is what connects these two concepts, i.e. how does String being immutable help StringBuffer?
Thanks :)
Because Strings are immutable, to manipulate Strings, such as to concatenate Strings, you have to create new String objects, since obviously, you can't change the state of existing String objects. Whereas with a StringBuffer or StringBuilder, you create one object and simply change its state. If you're doing some major String concatenation in a for loop for instance, this object creation can get very expensive.
That being said, I see many posts here critical of simple String concatenation that don't involve large-scale concatenation, and in that situation using a StringBuffer or StringBuilder is an example of premature and unnecessary optimization.
Also note that you should use StringBuilder preferentially over StringBuffer unless your application needs to access the object in multiple threads and doesn't mind the extra overhead that this incurs.
What it meant to say to is that since String is immutable therefore it is better to use StringBuffer (or StringBuilder) for String manipulation since you're not creating new object every time you change underlying String.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With