"StringBuffer is synchronized (or thread-safe) and StringBuilder is not", why does this make StringBuffer methods slower?

12,615

Solution 1

There is some small overhead acquiring and releasing even an uncontended lock, and lock elision won't work in StringBuffer even if most instances are not used cross-thread because an instance could be.

See http://book.javanb.com/java-threads-3rd/jthreads3-CHP-5-SECT-1.html for a description of what the VM has to do when acquiring and releasing locks.

Solution 2

Making sure things are running in synch. Or, more to the point, out of synch. Synchronizing a method call means two different invocations of that method (on that object if it is not static) have to take turns entering the method. Thread B cannot enter method synchMeth until Thread A (already in the method) has finished.

The checks for whether a synchronized block has been locked or not, and by whom, take extra time.

Solution 3

Read this from JavaDoc

StringBuilder class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

You must read this article on StringBuffer vs. StringBuilder performance comparison

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, {StringBuilder}. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

Additional Useful Link : Difference between StringBuffer and StringBuilder class.

Share:
12,615
Shailesh Tainwala
Author by

Shailesh Tainwala

Updated on June 05, 2022

Comments

  • Shailesh Tainwala
    Shailesh Tainwala over 1 year

    After reading this - What does 'synchronized' mean? I was still unable to understand why StringBuffer would be slower than StringBuilder in a thread-safe environment. What extra time-consuming work does StringBuffer have to do that makes it slower?