Difference between StringBuilder and StringBuffer

2018-12-31 02:24发布

What is the main difference between StringBuffer and StringBuilder? Is there any performance issues when deciding on any one of these?

30条回答
裙下三千臣
2楼-- · 2018-12-31 02:58

Better use StringBuilder since it is not synchronized and therefor better performance. StringBuilder is a drop-in replacement of the older StringBuffer.

查看更多
只若初见
3楼-- · 2018-12-31 02:58

StringBuffer:

  • Multi-Thread
  • Synchronized
  • Slow than StringBuilder

StringBuilder

  • Single-Thread
  • Not-Synchronized
  • Faster than ever String
查看更多
栀子花@的思念
4楼-- · 2018-12-31 03:00

StringBuffer is synchronized, but StringBuilder is not. As a result, StringBuilder is faster than StringBuffer.

查看更多
姐姐魅力值爆表
5楼-- · 2018-12-31 03:01

Since StringBuffer is synchronized, it needs some extra effort, hence based on perforamance, its a bit slow than StringBuilder.

查看更多
梦寄多情
6楼-- · 2018-12-31 03:02

String is an immutable object which means the value cannot be changed where as StringBuffer is mutable.

The StringBuffer is Synchronized hence thread safe where as StringBuilder is not and suitable for only single threaded instances.

查看更多
路过你的时光
7楼-- · 2018-12-31 03:02

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.

查看更多
登录 后发表回答