Comparing StringBuiler with StringBuffer

StringBuilder is a replacement for the thread-safe StringBuffer class. It works much faster as it has no synchronized methods. So, if you are doing lots of String operations in a single thread, you will gain a lot of performance when using this class.

Here’s a comparison.

Main.java:

public class Main
{
   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<100000; 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<100000; i++) {
         sb.append((char) 'a');
      }
      System.out.println("StringBuilder test: " + (System.nanoTime() - startTime));
   }
}

outputs:

StringBuffer test: 12849957
StringBuilder test: 8935494