StringBuilder vs StringBuffer

Let’s discuss StringBuilder vs StringBuffer in Java. StringBuilder Class and StringBuffer Class both classes are mutable classes, unlike the String class which is immutable.

The main difference between StringBuffer and StringBuilder can be explained on the basis of four parameters, synchronization, speed, thread-safety, and availability.

StringBuffer is synchronized and that’s why thread-safe, but StringBuilder is not synchronized, not thread-safe and that’s why StringBuilder is fast in execution as compared to StringBuffer class in Java.


StringBuilder vs StringBuffer

Let’s discuss the difference in details.

  1. StringBuilder is a non-synchronized version of StringBuffer class. Methods in StringBuilder e.g. all overloaded version of append() method is not synchronized.
  2. StringBuilder is definitely faster than StringBuffer because of no overhead of acquiring and releasing locks associated with synchronized methods.
  3. StringBuffer is thread-safe and StringBuilder is not. You can not share Instances of StringBuilder class between multiple threads. If such synchronization is required then it is better to use StringBuffer class.
  4. StringBuffer is old class, it’s there in JDK from very first release, while StringBuilder is relatively newer class, introduced much later in release of JDK 1.5
  5. Another interesting fact to know about both of this class is that, when you do String concatenation using + operator, Java internally convert that call to corresponding StringBuilder append() method class.

    For example – “one” + “two” + “three” will be converted to newStringBuilder().append(“one”).append(“two”).append(“three”).


Selenium Automation Video Testing:


Example of StringBuffer and StringBuilder Execution Speed 

As we know stringBuilder is faster then StringBuffer because StringBuilder is not thread-safe. Let’s compare the execution speed of both of the classes.

Output :

Total time taken by StringBuffer in Appending String is : 16ms
Total time taken by StringBuilder in Appending String is : 10ms


Please note above program Execution time depends on your server or system configuration and performance because JVM takes to memory from system RAM to perform the execution.

My  Configuration is –

Operating system –  64-bit  

Processor –                i7

RAM  –                         8 GB

This execution time may increase or minimize on your system. It’s all depends on your system configuration. But a point to be noted is StringBuilder took less time as compared to StringBuffer class in Java. So we have seen StringBuilder class is fast in execution as compared to StringBuilder class. 

0 Comment

Leave a Reply