Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Difference between StringBuilder and StringBuffer

What is the primary distinction between StringBuffer and StringBuilder? Is there any performance issues when deciding on any of these?
by

2 Answers

espadacoder11
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.
kshitijrana14
StringBuffer is synchronized, StringBuilder is not.

Login / Signup to Answer the Question.