StringBuffer is synchronized, and StringBuilder is not. It is the main difference between StringBuffer and StringBuilder.
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.
总结:单线程用StringBuilder,更快。多线程情况下用StringBuffer,保证线程安全。