Difference between StringBuffer and StringBuilder in Java

September 11, 2016

First, we have to remember that String is immutable and final in Java. Every modification of String (concatenation, substring, converting into lowercase or uppercase) creates a new String object. StringBuffer and StringBuilder are classes which allow us to manipulate String without creating garbage.

Append method implementations

What is the difference between them? Let’s look at the implementations of the method append(int) from StringBuffer and StringBuilder.

StringBuffer:

StringBuilder:

Because each method of StringBuffer is synchronized, it is thread-safe. However, because of that, it’s also slower. StringBuilder provides an API compatible with StringBuffer, but it is more efficient, as it has no synchronized methods.

Performance test

Let’s do a performance test of those two classes. The code below measures the time of 108 appends of a single char ‘a’.

Result:

The result shows that execution time of StringBuilder’s methods is almost six times faster than StringBuffer’s methods. That is the reason why we should use StringBuilder rather than StringBuffer.

Click here to add a comment

Leave a comment: