What is the main difference between StringBuffer
and StringBuilder
?
Is there any performance issues when deciding on any one of these?
StringBuilder is not thread safe. String Buffer is. More info here.
EDIT: As for performance , after hotspot kicks in , StringBuilder is the winner. However , for small iterations , the performance difference is negligible.
Difference between StringBuffer and StringBuilder Source:
StringBuilder is faster than StringBuffer because it's not synchronized
.
Here's a simple benchmark test:
public class Main {
public static void main(String[] args) {
int N = 77777777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = N; i --> 0 ;) {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = N; i > 0 ; i--) {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
}
}
A test run gives the numbers of 2241 ms
for StringBuffer
vs 753 ms
for StringBuilder
.
But needed to get the clear difference with the help of an example?
StringBuffer or StringBuilder
Simply use StringBuilder
unless you really are trying to share a buffer between threads. StringBuilder
is the unsynchronized (less overhead = more efficient) younger brother of the original synchronized StringBuffer
class.
StringBuffer
came first. Sun was concerned with correctness under all conditions, so they made it synchronized to make it thread-safe just in case.
StringBuilder
came later. Most of the uses of StringBuffer
were single-thread and unnecessarily paying the cost of the synchronization.
Since StringBuilder
is a drop-in replacement for StringBuffer
without the synchronization, there would not be differences between any examples.
If you are trying to share between threads, you can use StringBuffer
, but consider whether higher-level synchronization is necessary, e.g. perhaps instead of using StringBuffer, should you synchronize the methods that use the StringBuilder.
StringBuffer
is synchronized, but StringBuilder
is not. As a result, StringBuilder
is faster than StringBuffer
.
Basically, StringBuffer
methods are synchronized while StringBuilder
are not.
The operations are "almost" the same, but using synchronized methods in a single thread is overkill.
That's pretty much about it.
Quote from StringBuilder API:
This class [StringBuilder] provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
So it was made to substitute it.
The same happened with Vector
and ArrayList
.