Skip to content

Commit

Permalink
encoding/json: optimize marshal for quoted string
Browse files Browse the repository at this point in the history
Since Go 1.2 every string can be marshaled to JSON without error even if it
contains invalid UTF-8 byte sequences. Therefore there is no need to use
Marshal again for the only reason of enclosing the string in double quotes.
Not using Marshal here also removes the error check as there has not been a
way for Marshal to fail anyway.

Additionally, this code runs significantly faster for quoted string fields
(30 - 45% in my measurements, depending on the length of the string that is
processed).

Fixes: #34154
  • Loading branch information
breml committed Sep 6, 2019
1 parent 547021d commit d417e71
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/encoding/json/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -601,11 +601,11 @@ func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) {
return
}
if opts.quoted {
sb, err := Marshal(v.String())
if err != nil {
e.error(err)
}
e.string(string(sb), opts.escapeHTML)
b := make([]byte, 0, v.Len()+2)
b = append(b, '"')
b = append(b, []byte(v.String())...)
b = append(b, '"')
e.stringBytes(b, opts.escapeHTML)
} else {
e.string(v.String(), opts.escapeHTML)
}
Expand Down

0 comments on commit d417e71

Please sign in to comment.