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

Shailesh Tainwala picture Shailesh Tainwala · Jun 9, 2011 · Viewed 12.6k times · Source

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?

Answer

Mike Samuel picture Mike Samuel · Jun 9, 2011

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.