Thursday, 13 July 2017

StringBuffer vs StringBuilder in java ~ foundjava

Difference between StringBuffer and StringBuilder

There are many differences between StringBuffer and StringBuilder. A list of differences between StringBuffer and StringBuilder are given below:
No.StringBufferStringBuilder
1)StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2)StringBuffer is less efficient than StringBuilder.StringBuilder is more efficient than StringBuffer.

StringBuffer Example

  1. public class BufferTest{  
  2.     public static void main(String[] args){  
  3.         StringBuffer buffer=new StringBuffer("hello");  
  4.         buffer.append("java");  
  5.         System.out.println(buffer);  
  6.     }  
  7. }  
hellojava

StringBuilder Example

  1. public class BuilderTest{  
  2.     public static void main(String[] args){  
  3.         StringBuilder builder=new StringBuilder("hello");  
  4.         builder.append("java");  
  5.         System.out.println(builder);  
  6.     }  
  7. }  
hellojava

Performance Test of StringBuffer and StringBuilder

Let's see the code to check the performance of StringBuffer and StringBuilder classes.
  1. public class ConcatTest{  
  2.     public static void main(String[] args){  
  3.         long startTime = System.currentTimeMillis();  
  4.         StringBuffer sb = new StringBuffer("Java");  
  5.         for (int i=0; i<10000; i++){  
  6.             sb.append("Tpoint");  
  7.         }  
  8.         System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
  9.         startTime = System.currentTimeMillis();  
  10.         StringBuilder sb2 = new StringBuilder("Java");  
  11.         for (int i=0; i<10000; i++){  
  12.             sb2.append("Tpoint");  
  13.         }  
  14.         System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
  15.     }  
  16. }  
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms

1 comment:

  1. Thank you for the useful blogs. This really helps me a lot.I have also made my site for beginners. Please do check my website too.
    https://www.codingtag.com
    btw, if ANY IDE in ANY language Please suggestso that I could try to explain it on my website.
    Just sayin... :D

    ReplyDelete