开发者

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

开发者 https://www.devze.com 2023-03-11 08:39 出处:网络
After reading this - What does 'synchronized' mean? I was still unable to u开发者_Go百科nderstand why StringBuffer would be slower than StringBuilder in a thread-safe environment. What extra t

After reading this - What does 'synchronized' mean? I was still unable to u开发者_Go百科nderstand 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?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消