Skip to content

Commit d4bf400

Browse files
committed
encoding/json: optimize marshal for quoted string
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).
1 parent 547021d commit d4bf400

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

src/encoding/json/encode.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -601,11 +601,11 @@ func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) {
601601
return
602602
}
603603
if opts.quoted {
604-
sb, err := Marshal(v.String())
605-
if err != nil {
606-
e.error(err)
607-
}
608-
e.string(string(sb), opts.escapeHTML)
604+
b := make([]byte, 0, v.Len()+2)
605+
b = append(b, '"')
606+
b = append(b, []byte(v.String())...)
607+
b = append(b, '"')
608+
e.stringBytes(b, opts.escapeHTML)
609609
} else {
610610
e.string(v.String(), opts.escapeHTML)
611611
}

0 commit comments

Comments
 (0)