String, StringBuffer & StringBuilder

Java provides us String , StringBuffer & StringBuilder.

So, what is the basic differences between them?
Well , the answer is a theoretical one.

String is immutable, where, StringBuffer & StringBuilder are not.
(To see how String is mutable, see this post - Strings are immutable).

Now, what is the 
Difference between StringBuffer & StringBuilder?
The answer is :
StringBuffer is synchronized & StringBuilder is not.

So, performance wise, StringBuilder > StringBuffer > String (fastest to slowest)

So, When String , StringBuffer & StringBuilder should be used?

1. Use String, when the object is not changing frequently. In this case String gives a better performance, because, while creating a String, it searches String Constant Pool first & if it doesn't exist, then creates a new object. So, memory usage is optimum. When you are doing multiple operation with a string always use StringBuffer or StringBuilder

2. Use StringBuilder, if the object is not used by multiple threads (StringBuilder is not synchronized).

3. Use StringBuffer, if the objects is going to be used by multiple threads in the application. Because, in case of multi-threading, we need synchronization & StringBuffer is synchronized by default.


Happy Learning !!

No comments :

Post a Comment