Difference between StringBuilder and StringBuffer

后端 未结 30 2387
独厮守ぢ
独厮守ぢ 2020-11-21 15:06

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

30条回答
  •  清酒与你
    2020-11-21 15:46

    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.

提交回复
热议问题