Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Explain: why String immutable make StringBuffer MORE efficient

I have read in a Java book that says:

Because a String is immutable, using StringBuffer is 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 :)

like image 842
hqt Avatar asked Jul 28 '26 06:07

hqt


2 Answers

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.

like image 88
Hovercraft Full Of Eels Avatar answered Jul 29 '26 19:07

Hovercraft Full Of Eels


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.

like image 25
anubhava Avatar answered Jul 29 '26 20:07

anubhava