Why you should use StringBuilder instead of StringBuffer in Android for better performance?

By | February 25, 2018

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap.

StringBuffer has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe.Due to this it does not allow two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property. Thus StringBuilder is faster than the StringBuffer when calling the same methods of each class.

String Buffer can be converted to the string by using toString() method.

StringBuffer mString = new StringBuffer("Hello") ;
mString = new StringBuffer("Coderz Heaven");

StringBuilder

StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also be modified. The main difference between the StringBuffer and StringBuilder is that

StringBuilder is also not thread safe.
StringBuilder is fast as it is not thread safe.

StringBuilder values can also be modified and are stored in Heap.

StringBuilder str2 = new StringBuilder("Hello Coderz Heaven");
str2 = new StringBuilder("coderzheaven.com");

StringBuffer is synchronised as compared to StringBuilder. So StringBuilder is faster than StringBuffer.

 

Let me know what you think @coderzheaven@gmail.com

Leave a Reply

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