When to Use StringBuffer and StringBuilder class in Java Programming

(Last Updated On: February 20, 2017)

We should use StringBuffer for multi-threaded java program or else Stringbuilder class. The difference between StringBuffer and StringBuilder class in java is that StringBuffer is synchronized, whereas, StringBuilder is not.

In multithreading application, if a buffer is shared among multiple threads, then we should consider using StringBuffer as all of its methods are synchronized and hence thread safe. Otherwise, consider String Builder.

Note that if a buffer is not shared, always use StringBuilder in multithreaded application also, to avoid performance issue (speed). In fact, performance difference we can see only if the buffer is called repeatedly in a loop.

Lets do the performance test using StringBuffer and StringBuilder class with a java code example. We will use a huge loop for both class to add  a string. Note that we will be adding the same string i.e. “Performance Testing” for both classes.

As StringBuffer is synchronized, it will take more time to execute than StringBuilder.

 

 

OUTPUT:

Execution time of StringBuffer: 31ms
Execution time for StringBuilder: 16ms

Note that output may vary but execution time of String buffer class should always be greater than Strung builder