Difference between StringBuffer and StringBuilder in java

In this post, we will see difference between StringBuffer and StringBuilder in java

StringBuffer vs StringBuilder


Parameter
StringBuffer
StringBuilder
Thread-safe
StringBuffer is thread safe. Two threads can not call methods of StringBuffer simultaneously.
StringBuilder is not thread safe, so two threads can call methods of StringBuilder simultaneously. 
Performance
It is less performance efficient as it is thread-safe
It is more performance efficient as it is not thread-safe.

Performance comparison between StringBuffer and StringBuilder in single thread environment

package org.arpit.java2blog;

public class StringBuilderAndBufferMainTest {

 public static void main(String[] args) {
  
     long startTime = System.currentTimeMillis();  
        StringBuffer sb = new StringBuffer("Java");  
        for (int i=0; i<100000; i++){  
            sb.append("2Blog");  
        }  
        System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
        startTime = System.currentTimeMillis();  
        StringBuilder sbuilder = new StringBuilder("Java");  
        for (int i=0; i<100000; i++){  
         sbuilder.append("2Blog");  
        }  
        System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  

 }

}
When you run above program, you may get below output:
Time taken by StringBuffer: 21ms
Time taken by StringBuilder: 9ms

You can go through core java interview questions for more such questions.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012