What is the main difference between StringBuffer and StringBuilder?
Is there any performance issues when deciding on any one of these?
Check the internals of synchronized append method of StringBuffer and non-synchronized append method of StringBuilder.
StringBuffer:
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}
public synchronized StringBuffer append(Object obj) {
super.append(String.valueOf(obj));
return this;
}
public synchronized StringBuffer append(String str) {
super.append(str);
return this;
}
StringBuilder:
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
public StringBuilder append(Object obj) {
return append(String.valueOf(obj));
}
public StringBuilder append(String str) {
super.append(str);
return this;
}
Since append is synchronized, StringBuffer has performance overhead compared to StrinbBuilder in multi-threading scenario. As long as you are not sharing buffer among multiple threads, use StringBuilder, which is fast due to absence of synchronized in append methods.