What is the difference between StringBuilder and StringBuffer in Java
In this tutorial we will understand the difference between StringBuilder and StringBuffer in Java.
First lets see the similarities: Both StringBuilder and StringBuffer are mutable. That means you can change the content of them, with in the same location.
Differences: StringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable but not synchronized by default.
Meaning of synchronized (synchronization): When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem.
When to use what?
StringBuffer: WStringBuffer is synchronized i.e. thread safe. It means two threads can’t call the methods of StringBuffer simultaneously.
StringBuffer is less efficient than StringBuilder.
StringBuilder: StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
StringBuilder is more efficient than StringBuffer.
Note: Don’t use StringBuffer unnecessarily, i.e., don’t use it if only one thread is modifying and accessing it because it has lot of locking and unlocking code for synchronization which will unnecessarily take up CPU time. Don’t use locks unless it is required.
StringBuilder is faster than StringBuffer because it’s not synchronized. Here’s a simple 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.