What is the main difference between StringBuffer and StringBuilder? Is there any performance issues when deciding on any one of these?
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
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.
StringBuilder was introduced in Java 1.5 so it won't work with earlier JVMs.
From the Javadocs:
StringBuilder class 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.
StringBuffer - Synchronized hence threadsafe - thread safe hence slow -
StringBuilder - Introduced in java 5.0 - Asynchronous hence fast & efficient - User explicitly need to synchronized it, if he wants - You can replace it will StringBuilder without a any other change
StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands as needed. Related classes: String, CharSequence.
StringBuilder was added in Java 5. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.
StringBuffer is a synchroiz but StringBuilder is not and the StringBuilder is faster than the StringBuffer that what i know about it for naw
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 ;) {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
}
}
A test run gives the numbers of 2241 ms
for StringBuffer
vs 753 ms
for StringBuilder
.