0

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???

Nils von Barth
  • 3,239
  • 2
  • 26
  • 27
JustFF
  • 115
  • 1
  • 1
  • 6

1 Answers1

2

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.

codeaholicguy
  • 1,671
  • 1
  • 11
  • 18
  • The main point between StringBuffer and StringBuilder is that StringBuffer is synchronized, StringBuilder is not. – sp00m Jun 18 '15 at 09:28
  • 1
    @sp00m its about StringWriter and StringBuffer dude, please read the question carefully. – codeaholicguy Jun 18 '15 at 09:30
  • @codeaholicguy Confusion is caused by title which is "why does gson use stringbuffer". But you are right, after reading question it is clear that it is about StringWriter. – Pshemo Jun 18 '15 at 09:32
  • @Pshemo yes, I had a litle bit confusion at the first time but after read the source code, I guested that he want to ask about StringWriter and StringBuffer :) – codeaholicguy Jun 18 '15 at 09:35
  • You write "`StringWriter` is a Writer, it is nothing like `StringBuffer`" ...except `StringWriter` uses a `StringBuffer` internally, though just with `append`. Yes, the interfaces differ, but since this question is about implementation, the comparison is fair, and asking why not use `StringBuilder` (instead of `StringWriter`, which uses `StringBuffer`) is a perfectly reasonable question. – Nils von Barth Sep 01 '15 at 03:18