Difference between StringBuilder and StringBuffer classes

We use the StringBuffer and StringBuilder classes when we work with mutable String objects since the String class is immutable.

Differences between the StringBuffer and StringBuilder classes are:

                                   StringBuffer                                  StringBuilder
  StringBuffer is synchronized i.e. thread-safe. It means two threads can’t call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread-safe. It means two threads can call the methods of StringBuilder simultaneously.
  StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.


StringBuffer vs StringBuilder Performance Testing

See in the following example the differences in performance between these two classes:

class Test {

  public static void main(String[] args) {
    long startTime = System.currentTimeMillis();
    StringBuffer stringBuffer = new StringBuffer("Java");

    for (int i = 0; i < 8000000; i++) {
      stringBuffer.append("Programming");
    }

    System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");
    startTime = System.currentTimeMillis();

    StringBuilder stringBuilder = new StringBuilder("Java");

    for (int i = 0; i < 8000000; i++) {
      stringBuilder.append("Programming");
    }

    System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");
  }
}
Output: Time taken by StringBuffer: 324ms Time taken by StringBuilder: 208ms


The program output shows that the 
StringBuffer class took longer to complete the given task.

Conclusion:
If we need to work with a mutable String, and we don’t care if it’s not thread-safe, then we should choose StringBuilder.

That was all regarding StringBuffer vs StringBuilder. Proceed to the next lesson.

Happy Learning!

 

Leave a Reply

Your email address will not be published. Required fields are marked *