StringBuffer is synchronized, StringBuilder is not.
StringBuffer is synchronized, StringBuilder is not.
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 ; i--) {
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.
java - String, StringBuffer, and StringBuilder - Stack Overflow
In Java, why use StringBuilder instead of Strings?
[Java] What exactly is stringBuilder and why use it instead of a traditional String?
String Builder vs String Writer/Reader use case
#1 is probably the way to go. If you're worried about performance, use a benchmark to compare them.
More on reddit.comMutability Difference:
String is immutable. If you try to alter their values, another object gets created, whereas StringBuffer and StringBuilder are mutable, so they can change their values.
Thread-Safety Difference:
The difference between StringBuffer and StringBuilder is that StringBuffer is threadsafe. So when the application needs to be run only in a single thread, then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.
Situations:
- If your string is not going to change use a String class, because a
Stringobject is immutable. - If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a
StringBuilderis good enough. - If your string can change, and will be accessed from multiple threads, use a
StringBufferbecauseStringBufferis synchronous so you have thread-safety.
- You use
Stringwhen an immutable structure is appropriate; obtaining a new character sequence from aStringmay carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated). - You use
StringBuilderwhen you need to create a mutable character sequence, usually to concatenate several character sequences together. - You use
StringBufferin the same circumstances you would useStringBuilder, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).
See an example here.