Difference between StringBuilder and StringBuffer

In recent posts, we have learned about the StringBuffer class and the StringBuilder class. Both classes are used to create a mutable string in java. In this post, we will discuss the difference between StringBuilder and StringBuffer in java.

Difference between StringBuilder and StringBuffer

1.  StringBuffer class introduced in Java 1.4 versions. But the StringBuilder class introduced in 1.5 versions of java.

2. StringBuffer class has a synchronized method but the StringBuilder class doesn’t have synchronized methods.

3. StringBuffer class is thread safe but the StringBuilder class is not Thread safe.

4. StringBuffer class is slower than the StringBuilder class.

public class PerformanceTest  
{  
    public static void main(String[] args)   
    {  
        
    	long startTime = System.currentTimeMillis();  
        StringBuffer strbuffer = new StringBuffer("Hello");  
        for (int i = 0; i < 10000; i++)   
        {  
            strbuffer.append(i);  
        }  
        System.out.println("Time to append: " + (System.currentTimeMillis() - startTime) + "ms");  
       
        startTime = System.currentTimeMillis();  
        StringBuilder strbuilder = new StringBuilder("Hello");  
        for (int i = 0; i < 10000; i++) 
        {  
            strbuilder.append(i);  
        }  
        System.out.println("Time to append: " + (System.currentTimeMillis() - startTime) + "ms");  
    }  
}

Output: Time to append: 6ms
Time to append: 4ms

Leave a Comment