StringBuilder vs StringBuffer in Java

In Java, to represent strings, there are three ways: String, StringBuffer, and StringBuilder. Strings are immutable(once created cannot be changed) in Java, whereas StringBuffer and StringBuilder classes are mutable.


           StringBuffer is mutable, which means one can change the value of the object. In the same way, StringBuilder is also mutable, it can also be modified. The main difference between the StringBuffer and StringBuilder is that StringBuilder is not thread-safe.

StringBuilder vs StringBuffer

  •  StringBuffer class is synchronized( Only one thread at a time may perform required action)whereas StringBuilder is non-synchronized.
  • StringBuilder is more efficient than the StringBuffer class as it is not thread-safe.

Example code to demonstrate the above statements:

import java.util.*;
public class StringBuffervsBuilder{  
    public static void main(String[] args){  
        long startingTime = System.currentTimeMillis();  
        StringBuffer sb = new StringBuffer("Code");  
        for (int i=0; i<100000; i++){  
            sb.append("Speedy");  
        }  
        System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startingTime) + "ms");  

        startingTime = System.currentTimeMillis();  
        StringBuilder sb2 = new StringBuilder("Code");  
        for (int i=0; i<100000; i++){  
            sb2.append("Speedy");  
        }  
        System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startingTime) + "ms");  
    }  
}

output:

Time taken by StringBuffer: 7ms
Time taken by StringBuilder: 3ms

Finally, we can say that:

  • StringBuffer and StringBuilder both are similar.
  • StringBuilder is faster and preferred over StringBuffer for the single-threaded program(as above example code).
  •  StringBuffer is used when thread safety is needed.

Leave a Reply

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