From 0984d1ec09b9fe95b917c1a22521da45ef4c43c6 Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Sat, 7 Dec 2024 16:38:00 -0800 Subject: [PATCH] Optimize Encoder.WriteValue for object names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit By specifying the isVerbatim flag to names.insertQuoted, the method can avoid unquoting the name since it knows that it only needs to strip off the surrounding double quotes. Performance: name old speed new speed delta Testdata/CanadaGeometry/Encode/Value/Buffered 1.12GB/s ± 0% 1.15GB/s ± 3% ~ (p=0.151 n=5+5) Testdata/CitmCatalog/Encode/Value/Buffered 1.76GB/s ± 0% 1.99GB/s ± 1% +13.19% (p=0.008 n=5+5) Testdata/GolangSource/Encode/Value/Buffered 793MB/s ± 4% 949MB/s ± 1% +19.68% (p=0.008 n=5+5) Testdata/StringEscaped/Encode/Value/Buffered 228MB/s ± 1% 229MB/s ± 0% ~ (p=0.421 n=5+5) Testdata/StringUnicode/Encode/Value/Buffered 983MB/s ± 0% 1014MB/s ± 1% +3.12% (p=0.008 n=5+5) Testdata/SyntheaFhir/Encode/Value/Buffered 1.39GB/s ± 4% 1.65GB/s ± 1% +18.43% (p=0.008 n=5+5) Testdata/TwitterStatus/Encode/Value/Buffered 1.03GB/s ± 1% 1.23GB/s ± 0% +19.81% (p=0.008 n=5+5) --- jsontext/encode.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/jsontext/encode.go b/jsontext/encode.go index c9c5a5c..9c26a3c 100644 --- a/jsontext/encode.go +++ b/jsontext/encode.go @@ -716,7 +716,8 @@ func (e *encoderState) reformatObject(dst []byte, src Value, depth int) ([]byte, return dst, n, io.ErrUnexpectedEOF } m := jsonwire.ConsumeSimpleString(src[n:]) - if m > 0 { + isVerbatim := m > 0 + if isVerbatim { dst = append(dst, src[n:n+m]...) } else { dst, m, err = jsonwire.ReformatString(dst, src[n:], &e.Flags) @@ -724,9 +725,9 @@ func (e *encoderState) reformatObject(dst []byte, src Value, depth int) ([]byte, return dst, n + m, err } } - // TODO: Specify whether the name is verbatim or not. - if !e.Flags.Get(jsonflags.AllowDuplicateNames) && !names.insertQuoted(src[n:n+m], false) { - return dst, n, newDuplicateNameError(src[n : n+m]) + quotedName := src[n : n+m] + if !e.Flags.Get(jsonflags.AllowDuplicateNames) && !names.insertQuoted(quotedName, isVerbatim) { + return dst, n, newDuplicateNameError(quotedName) } n += m