Computer >> Computer tutorials >  >> Programming >> Java

How can we compare a StringBuilder with StringBuffer in Java?


The StringBuffer objects are generally safe to use in a multi-threaded environment where multiple threads may be trying to access the same StringBuffer object at the same time. The StringBuilder is a replacement for the thread-safe StringBuffer class and it works much faster as it has no synchronized methods. If we are doing lots of String operations in a single thread, we can gain a lot of performance when using this class.

Example

public class CompareBuilderwithBufferTest {
   public static void main(String []args) {
      stringBufferTest();
      stringBuilderTest();
   }
   public static void stringBufferTest() {
      long startTime = System.nanoTime();
      StringBuffer sb = new StringBuffer();
      for (int i=0; i < 1000; i++) {
         sb.append((char) 'a');
      }
      System.out.println("StringBuffer test: " + (System.nanoTime() - startTime));
   }
   public static void stringBuilderTest() {
      long startTime = System.nanoTime();
      StringBuilder sb = new StringBuilder();
      for (int i=0; i < 1000; i++) {
         sb.append((char) 'a');
      }
      System.out.println("StringBuilder test: " + (System.nanoTime() - startTime));
   }
}

Output

StringBuffer test: 192595
StringBuilder test: 85733