Tuesday, 8 March 2016

Difference between StringBuffer and StringBuilder in java

Since String is immutable object in java, i.e it can't be changed so if we want to operate on string for example perform concatenate operation there must be someone to help. And the helper should be mutable (object value can be changed repeatedly). The rescuer provided by Java are StringBuffer and StringBuilder. So if both are mutable and perform same task then what is the difference between them. Let's find out.
  • StringBuffer() - If thread safety is your concern then use StringBuffer() method because each method in it is synchronized. And due to the synchronization effect, it doesn't allow two threads to access same method simultaneously. Only one thread can access a method at a time.
     But this thread safety in StringBuffer comes at the cost of performance making it slower in terms of performing operation as compared to StringBuilder. 
  • StringBuilder() - If you need faster operation and are least bothered about thread safety then use StringBuilder. It's obvious to be fast because it is not concerned about additional task of performing thread safety. 
* Both store the created object in heap.

You may also like to know about :

No comments:

Post a Comment

If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.