Why does gson use StringWriter in method toJSONString()?

444 views Asked by At

From source code:

public String toJson(Object src, Type typeOfSrc) {
    StringWriter writer = new StringWriter();
    this.toJson((JsonElement)this.toJsonTree(src, typeOfSrc), (Appendable)writer);
    return writer.toString();
}

StringWriter uses StringBuffer internally; why not use StringBuilder for better performance???

1

There are 1 answers

5
codeaholicguy On

StringWriter is a Writer, it is nothing like StringBuffer and the purpose of each is so far from the other that it would be easier to explain the similarities which would be relegated to similarities that exist between all Objects. You should use a StringWriter when you want a Writer (a character stream). You should use a StringBuffer when you need a mutable buffer for constructing Strings, or must construct a String in such a way that it cannot be done using String's constructors.

They use it because they need a character stream.