Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuffer is obsolete?

In the book "Effective Java", Josh Bloch says that

StringBuffer is largely obsolete and should be replaced by the non-synchronized implementation 'StringBuilder'

.

But in my experience, I've still seen widespread use of the StringBuffer class. Why is the StringBuffer class now obsolete and why should StringBuilder be preferred over StringBuffer except for the increased performance due to non-synchronization?

like image 849
Varun Achar Avatar asked Jul 21 '11 11:07

Varun Achar


People also ask

What can I use instead of StringBuffer?

Actually for the example above you should use StringBuilder (introduced in Java 1.5) instead of StringBuffer - StringBuffer is little heavier as all its methods are synchronized.

Which is better StringBuffer or StringBuilder?

String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.

Why is StringBuffer so slow?

String Buffer: The performance in String buffer is slow because, in the environment of a string synchronized, the one thread only performs the operations without distributing the work to other threads.

Which is more time efficient StringBuilder or StringBuffer?

StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.


1 Answers

It's obsolete in that new code on Java 1.5 should generally use StringBuilder - it's very rare that you really need to build strings in a thread-safe manner, so why pay the synchronization cost?

I suspect code that you see using StringBuffer mostly falls into buckets of:

  • Written before Java 1.5
  • Written to maintain compatibility with older JDKs
  • Written by people who don't know about StringBuilder
  • Autogenerated by tools which don't know about StringBuilder
like image 142
Jon Skeet Avatar answered Oct 10 '22 21:10

Jon Skeet