With the introduction of StringBuilder in Java 5, use StringBuilder if you are in Java 5 or above. StringBuilder will be faster in most cases as it doesn’t perform synchronization.
What is the main difference between StringBuffer and StringBuilder in java?
StringBuffers are ThreadSafe. All the methods of a StringBuffer like append or insert are synchronized. Whereas methods in StringBuilder are not synchronized. Rest of the implementations are same.
But keep in mind most of the real world scenarios use Strings local to a thread. It is very rare that multiple Threads share and manipulate a single String at the same time. Hence generally speaking prefer using StringBuilder in place of StringBuffer.
A quick performance comparison between StringBuffer and StringBuilder is provided below.
To execute the below code StringBuffer took 7.7 milliseconds on average. Whereas StringBuilder took 4.25 milliseconds on average.
//StringBuffer b = new StringBuffer();
StringBuilder b = new StringBuilder();
for (int j = 0; j < 100000; j++) {
b.append("One").append(".").append(two).append(three);
}