Skip to content

perf: add opt-in fast paths for JSON escaping and unsigned integers - #158

Open
pnut2022 wants to merge 1 commit into
bytedance:masterfrom
pnut2022:optimize/serialize-and-uint-fast-paths
Open

pnut2022 wants to merge 1 commit into
bytedance:masterfrom
pnut2022:optimize/serialize-and-uint-fast-paths

Conversation

@pnut2022

Copy link
Copy Markdown

Changes

This adds two independent compile-time options for workloads with frequent JSON string escapes or repeated integer shapes. Both are off by default.

  • SONIC_ENABLE_SERIALIZE_OPT lets AVX2 serialization escape quotes and backslashes in groups within a 32-byte block. Blocks that need control-character or emoji escaping use the existing escape handler. The option also exposes WriteBuffer::ReleaseBuffer() for transferring ownership and SerializeFlags::kSerializeWriterStringGrowth for callers that want more headroom when writing large strings.
  • SONIC_ENABLE_PARSE_UINT_FASTPATH handles one- and two-digit unsigned object values and 16-digit unsigned array elements immediately followed by a delimiter. Other number shapes use the existing parser. Raw-integer parsing and SAX termination retain their existing behavior and offsets.

Benchmark

Median CPU time per document over nine runs of the repository's Encode_SonicDyn and Decode_SonicDyn benchmarks. Lower is faster. Each run was pinned to one logical CPU on an Intel Xeon Platinum 8582C (Linux x86-64 VM). The three binaries ran in rotating order, using Google Benchmark 1.9.5 with a minimum of 0.15 seconds per case. Builds used Clang 20.2.0, C++17, -O3 -DNDEBUG and static AVX2 (-mavx2 -mpclmul -mbmi -mlzcnt). The baseline is 3ecbef2. All encode timings use the default serialization flags.

Input / operation master (µs) PR, flags off (µs) PR, both on (µs) Both on vs. master
short_object / Decode 56.70 56.20 44.25 -22.0%
array16 / Decode 61.62 61.50 22.74 -63.1%
longer_object / Decode 61.83 57.13 61.10 -1.2%
dense_escapes / Encode 252.67 231.78 20.59 -91.9%
control_escapes / Encode 266.30 245.64 249.70 -6.2%
plain_strings / Encode 10.87 10.78 10.65 -2.0%
twitter / Decode 135.80 136.56 138.72 +2.2%
twitter / Encode 61.97 60.24 62.28 +0.5%
twitterescaped / Decode 395.39 399.07 394.33 -0.3%
twitterescaped / Encode 154.62 150.45 157.77 +2.0%
citm_catalog / Decode 807.64 797.43 824.68 +2.1%
citm_catalog / Encode 392.27 386.52 393.49 +0.3%

The largest gains were on inputs that repeatedly hit the new paths. Enabling the macros on the PR reduced dense-escape encoding from 231.78 to 20.59 µs, while four-digit object values took 6.9% longer (57.13 to 61.10 µs). Against master, the three repository JSON files ranged from 0.3% faster to 2.2% slower.

Reproduce the timing runs on Linux x86-64

From the PR checkout, build the existing benchmark against each header version. On systems with GCC 8's libstdc++, also pass -DCMAKE_CXX_STANDARD_LIBRARIES=-lstdc++fs to CMake.

set -eu
pr=$PWD
tmp=$(mktemp -d)
mkdir -p "$tmp/master" "$tmp/run/testdata"
git archive 3ecbef21a42ebc67ef1bbf7ba72d76c44472eee1 | tar -x -C "$tmp/master"
export CC=clang CXX=clang++
for v in master off on; do
  src=$pr
  flags=""
  if [ "$v" = master ]; then src="$tmp/master"; fi
  if [ "$v" = on ]; then flags="-DSONIC_ENABLE_SERIALIZE_OPT -DSONIC_ENABLE_PARSE_UINT_FASTPATH"; fi
  cmake -S "$src" -B "$tmp/$v-build" -DBUILD_BENCH=ON -DBUILD_UNITTEST=OFF \
    -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="$flags"
  cmake --build "$tmp/$v-build" --target bench -j
done

cd "$tmp/run"
for x in twitter twitterescaped citm_catalog; do ln -s "$pr/testdata/$x.json" testdata/; done
python3 - <<'PY'
import json
from pathlib import Path

out = Path("testdata")
cases = {
    "short_object": {"k" + str(i): i % 100 for i in range(4096)},
    "longer_object": {"k" + str(i): 1000 + i for i in range(4096)},
    "array16": [10**15 + i for i in range(4096)],
    "dense_escapes": [('abcd"ef\\' * 16)] * 1024,
    "control_escapes": [('\nbcd"ef\\' * 16)] * 1024,
    "plain_strings": ["abcdefgh" * 16] * 1024,
}
for name, data in cases.items():
    (out / (name + ".json")).write_text(json.dumps(data, separators=(",", ":")))
PY
filter='^((short_object|longer_object|array16)/Decode|(dense_escapes|control_escapes|plain_strings)/Encode|(twitter|twitterescaped|citm_catalog)/(Encode|Decode))_SonicDyn$'
versions=(master off on)
for ((r=0; r<9; r++)); do
  for ((i=0; i<3; i++)); do
    v=${versions[(r+i)%3]}
    taskset -c 24 "$tmp/$v-build/benchmark/bench" --benchmark_filter="$filter" \
      --benchmark_min_time=0.15s --benchmark_out_format=json --benchmark_out="$r-$v.json"
  done
done

Optional writer growth

With SONIC_ENABLE_SERIALIZE_OPT defined, appending two newline-filled strings (1 MiB, then 1.25 MiB) produced byte-identical 4,718,599-byte JSON arrays. The measured WriteBuffer::Capacity() after each string was 9,437,238 → 18,874,476 bytes with ordinary append, and 11,796,547 → 11,796,547 bytes with the extra growth flag. In this example, reserving 2.25 MiB more for the first string avoided a second buffer growth and reduced the final reserved capacity by 6.75 MiB.

Reproduce the writer-capacity comparison
#include <cstdio>
#include <string>

#include "sonic/sonic.h"

using namespace sonic_json;

template <SerializeFlags flags>
std::string check() {
  WriteBuffer wb;
  wb.Push<char>('[');
  for (size_t n : {1024u * 1024u, 1280u * 1024u}) {
    std::string text(n, '\n');
    Node node;
    node.SetString(text.data(), text.size());
    if (wb.Size() > 1) wb.Push<char>(',');
    if (node.Serialize<flags>(wb) != kErrorNone) std::abort();
    std::printf("%zu ", wb.Capacity());
  }
  wb.Push<char>(']');
  std::printf("bytes=%zu\n", wb.Size());
  return std::string(wb.Begin<char>(), wb.Size());
}

int main() {
  constexpr auto append = SerializeFlags::kSerializeAppendBuffer;
  auto a = check<append>();
  auto b = check<append | SerializeFlags::kSerializeWriterStringGrowth>();
  return a != b;
}
clang++ -std=c++17 -O3 -DNDEBUG -mavx2 -mpclmul -mbmi -mlzcnt \
  -DSONIC_ENABLE_SERIALIZE_OPT -Iinclude growth.cpp -o growth
./growth

Validation

  • With Clang 20, static AVX2 and AddressSanitizer, all 310 tests passed with both options off and all 314 passed with both options on.
  • The parser and SAX tests passed with both options enabled on static Westmere (Clang and AddressSanitizer) and x86 runtime dispatch (GCC 8.3), 57 tests in each build. The quote tests also passed on Westmere and with Clang x86 runtime dispatch.
  • A full parser smoke build with Clang 20 runtime dispatch encountered the same unresolved skip-function symbols on master and on this branch. ARM and RISC-V were not run locally.
  • The changed C++ files pass the repository's clang-format 14 check.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant