Skip to content

Commit b4da9fd

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). Fixes: #34154
1 parent 547021d commit b4da9fd

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-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
}

src/encoding/json/stream_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,27 @@ func TestEncoderSetEscapeHTML(t *testing.T) {
158158
}
159159
}
160160

161+
// https://golang.org/issue/34154
162+
func TestEncoderStringOptionSetEscapeHTMLFalse(t *testing.T) {
163+
value := struct {
164+
Bar string `json:"bar,string"`
165+
}{
166+
Bar: `<html>foobar</html>`,
167+
}
168+
want := `{"bar":"\"<html>foobar</html>\""}`
169+
170+
var buf bytes.Buffer
171+
enc := NewEncoder(&buf)
172+
enc.SetEscapeHTML(false)
173+
if err := enc.Encode(value); err != nil {
174+
t.Fatalf("Encode: %s", err)
175+
}
176+
if got := strings.TrimSpace(buf.String()); got != want {
177+
t.Errorf("SetEscapeHTML(false) Encode = %#q, want %#q",
178+
got, want)
179+
}
180+
}
181+
161182
func TestDecoder(t *testing.T) {
162183
for i := 0; i <= len(streamTest); i++ {
163184
// Use stream without newlines as input,

0 commit comments

Comments
 (0)