Comparision of StringBuffer and StringBuilder in Java

By Jyoti Singh Last updated : January 31, 2024

StringBuffer and StringBuilder in Java

StringBuffer and StringBuilder are two classes of Java, which are used for strings. These are used whenever there is a need for a lot of modification to Strings. StringBuffer and StringBuilder objects can be modified again and again.

Difference between StringBuffer and StringBuilder classes

The difference between StringBuffer and String Builder is that - The methods of StringBuilder class are not synchronized that is they are not thread safe as two threads can call the StringBuilder methods simultaneously. Whereas, StringBuffer class and its methods are thread-safe.

Which class is better to use StringBuffer or StringBuilder?

Both of the classes have their advantages and disadvantages. In general, it is better to use the StringBuilder class because the StringBuilder class is faster than StringBuffer.

Let's take an example to check which one is faster.

Example demonstrating the comparison between StringBuffer and StringBuilder classes

public class ExComparison2 {
  public static void main(String arg[]) {
    long st, et;
    StringBuffer str1 = new StringBuffer(); // String buffer class object
    st = System.currentTimeMillis(); // recording current time
    
    for (int i = 0; i < 1000000; i++) {
      //append method of string buffer add the data in string object.		
      str1.append("Testing StringBuffer ");
    }
    
    et = System.currentTimeMillis();
    System.out.println("String Buffer Takes " + (et - st) + " milliSeconds");
    //(et-st) shows the time taken by the String buffer.
    StringBuilder str2 = new StringBuilder(); //String Builder class object
    st = System.currentTimeMillis();
    
    for (int i = 0; i < 1000000; i++) {
      //append method of string buffer add the data in string object.
      str2.append("Testing StringBuffer ");
    }

    et = System.currentTimeMillis();
    System.out.println("String Builder Takes " + (et - st) + " milliSeconds");
    ////(et-st) shows the time taken by the String builder.
  }
}

Output

Comparision of  StringBuffer and StringBuilder in Java

As you can see StringBuilder takes less time than StringBuffer.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.