StringBuffer and StringBuilder in Java

In Java, in addition to the StringBuilder object, we also have a StringBuffer object with the same functionality as the StringBuilder object, but in reality it is thread-safe. This means that only one thread can access our StringBuffer object at a time.

Thread-safe ensures that our StringBuffer object is consistent when it is used in multiple threads, but this also means using StringBuffer to build a String will be slower.

Consider the following example:

StringBuffer and StringBuilder in Java

Obviously, you see the same code but using StringBuffer to build string will make our code much slower.

So, let’s consider the case where we use the StringBuffer, only use it in special cases only.

5/5 - (1 vote)

Add Comment