Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 646
Shailesh Tainwala Avatar asked Feb 14 '26 02:02

Shailesh Tainwala


1 Answers

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.

like image 135
Mike Samuel Avatar answered Feb 16 '26 15:02

Mike Samuel