Difference between StringBuilder and StringBuffer Difference between StringBuilder and StringBuffer java java

Difference between StringBuilder and StringBuffer


StringBuilder is faster than StringBuffer because it's not synchronized.

Here's a simple benchmark test:

public class Main {    public static void main(String[] args) {        int N = 77777777;        long t;        {            StringBuffer sb = new StringBuffer();            t = System.currentTimeMillis();            for (int i = N; i --> 0 ;) {                sb.append("");            }            System.out.println(System.currentTimeMillis() - t);        }        {            StringBuilder sb = new StringBuilder();            t = System.currentTimeMillis();            for (int i = N; i > 0 ; i--) {                sb.append("");            }            System.out.println(System.currentTimeMillis() - t);        }    }}

A test run gives the numbers of 2241 ms for StringBuffer vs 753 ms for StringBuilder.


Basically, StringBuffer methods are synchronized while StringBuilder are not.

The operations are "almost" the same, but using synchronized methods in a single thread is overkill.

That's pretty much about it.

Quote from StringBuilder API:

This class [StringBuilder] 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.

So it was made to substitute it.

The same happened with Vector and ArrayList.