Skip to content
Myr

perf: optimize AsciiJSON.Render method by using fmt.Appendf and reusing temp buffer (#4175)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

per: use bytesconv.BytesToString(ret) instead of string(str)

authored by Name · committed by GitHub · parent afa0c31 · Browse files · 1 file+7 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: 1911860538 <alxps1911@gmail.com>

Diff stats

1 file+7 added−4 removed

  • other:+7 added−4 removed

1 file+7 added−4 removed

modified:render/json.go+7 added-4 removed
149 unmodified lines
150 writeContentType(w, jsonpContentType)151}152153// Render (AsciiJSON) marshals the given interface object and writes it with custom ContentType.154func (r AsciiJSON) Render(w http.ResponseWriter) (err error) {154func (r AsciiJSON) Render(w http.ResponseWriter) error {155 r.WriteContentType(w)156 ret, err := json.Marshal(r.Data)157 if err != nil {158 return err159 }160161 var buffer bytes.Buffer162 escapeBuf := make([]byte, 0, 6) // Preallocate 6 bytes for Unicode escape sequences163164 for _, r := range bytesconv.BytesToString(ret) {163 cvt := string(r)165 if r >= 128 {165 cvt = fmt.Sprintf("\\u%04x", int64(r))166 escapeBuf = fmt.Appendf(escapeBuf[:0], "\\u%04x", r) // Reuse escapeBuf167 buffer.Write(escapeBuf)168 } else {169 buffer.WriteByte(byte(r))170 }167 buffer.WriteString(cvt)171 }172173 _, err = w.Write(buffer.Bytes())174 return err
19 unmodified lines