Skip to content

Optimize lazy views, dumps/dumpb, typed decoding, compressed input, and fields= - #27

Open
shelbaz wants to merge 1 commit into
simdjson:mainfrom
shelbaz:perf/optimizations
Open

shelbaz wants to merge 1 commit into
simdjson:mainfrom
shelbaz:perf/optimizations

Conversation

@shelbaz

@shelbaz shelbaz commented Dec 6, 2026

Copy link
Copy Markdown

Summary

This PR optimizes several hot paths across fastsimdjson without modifying vendored libraries or changing public behavior or parity with json, orjson, and msgspec:

  1. Lazy Object / Array views (src/fastsimdjson.cpp)

    • Lazily publish lock-free (std::atomic<void*>) open-addressed hash indices for repeated key lookups on Object views (>= 16 keys, preserving first-key-wins semantics for duplicate keys) and strided tape-offset indices for backward/random access on Array views (>= 32 elements).
    • Single-pass O(N) array_subscript slicing for both positive and negative steps, reusing a single Builder.
    • Compact-ASCII fast path in object_lookup.
  2. Serialization (dumps, dump, dumpb in src/fastsimdjson.cpp)

    • METH_FASTCALL | METH_KEYWORDS for dumps, stack-allocated cycle path, exact-type inline dispatch (PyUnstable_Long_IsCompact on 3.12+), fast separator modes, and GIL borrowed mode (with safe restart if a dict subclass or non-str key comparison runs Python code).
    • Share the thread-local EncodedKey cache across dumps/dump/dumpb (guarded by ensure_ascii_ok so \x7f and non-ASCII keys remain isolated between ensure_ascii=True and UTF-8 modes).
    • NEON / pure-SSE2 / scalar SIMD ASCII-escape scanners for Latin-1, UCS-2, and UCS-4 strings under ensure_ascii=True, plus a HEX_PAIRS lookup table.
    • Fast C++ encode_dict_sorted_str for dumps(..., sort_keys=True) and arena-backed OrjsonEncoder::encode_dict_collected with std::sort for string keys.
  3. Typed decoding (src/typed.h)

    • Open-addressed field_table + 64-bit length bitmask for O(1) field lookup and unknown-key rejection.
    • Direct PyMemberDescrObject slot writes (guarded by Py_IS_TYPE(out, tp)) for @dataclass(slots=True) and tp_alloc fast path for non-abstract object.__new__ dataclasses.
    • Zero-allocation C++ lookup tables for Enum and Literal values.
    • Direct scalar decode paths and specialized tight loops for List[int|float|str|bool] and Dict[str, str|int] on TapeSource; presized TypedDict.
  4. Compressed input (src/compressed.h, src/fastsimdjson.cpp)

    • Thread-local ThreadCache reusing libdeflate_decompressor, ZSTD_DCtx, and a padded scratch buffer (<= 4 MiB, freed by release() and thread exit).
    • Single-frame known-size unzstd fast path avoiding Frame vector and thread setup.
    • Zero-PyBytesObject decompression into RawOutput inside with_input_f (re-entrant via scratch ownership transfer, lazily wrapping into PyBytes only on json.loads fallback).
    • Fixes gunzip initial reservation when max_size=0 on empty gzip payloads.
  5. Streams / fields= & minify (src/fastsimdjson.cpp)

    • Single-pass extract_dom_walk over the compiled FieldNode tree and bitmask tracking in od_walk.
    • Avoid shrinking _PyBytes_Resize copy in minify when output is at least half the input size.

Benchmarks

Measured on Apple M1 Pro (arm64), Apple Clang 21.0.0, CPython 3.14.7 against simdjson-data/jsonexamples:

bench_dumps.py (standard corpus)

dumps geometric mean vs json.dumps improves from 5.38x → 8.44x (+57%):

Corpus file json.dumps dumps before dumps after Speedup dumpb after orjson
twitter.json 1,406.3 µs 438.5 µs 220.0 µs 1.99x 196.9 µs 273.0 µs
gsoc-2018.json 6,387.8 µs 1,706.0 µs 895.5 µs 1.91x 748.7 µs 1,088.3 µs
citm_catalog.json 2,634.0 µs 899.0 µs 517.2 µs 1.74x 393.6 µs 445.9 µs
github_events.json 162.1 µs 36.3 µs 23.3 µs 1.56x 19.1 µs 21.3 µs
mesh.json 8,402.8 µs 912.9 µs 676.0 µs 1.35x 590.4 µs 1,055.6 µs
canada.json 34,649.2 µs 2,464.0 µs 1,934.9 µs 1.27x 1,674.5 µs 2,242.8 µs

Subsystem highlights

Workload Before After Speedup
Lazy Array[::-1] (10,000 elements) 32,281.9 µs 128.9 µs 250.4x
Lazy Array[::-3] (10,000 elements) 10,816.5 µs 45.7 µs 236.7x
Lazy Array[rand] ×1,000 (10,000 elements) 2,239.0 µs 44.6 µs 50.2x
Lazy Object[k] ×1,000 (2,000-key object) 2,045.4 µs 116.5 µs 17.6x
Lazy citm["events"][k] (all 184 keys) 54.7 µs 9.7 µs 5.6x
dumps Latin-1 32K mostly-ASCII (ensure_ascii=True) 31.0 µs 1.9 µs 16.3x
dumps UCS-2 32K mostly-ASCII (ensure_ascii=True) 31.2 µs 3.6 µs 8.7x
dumps UCS-4 32K mostly-ASCII (ensure_ascii=True) 31.3 µs 5.9 µs 5.3x
dumps UCS-4 16K all-emoji (ensure_ascii=True) 87.8 µs 26.1 µs 3.4x
dumps(citm, sort_keys=True) 1,786.3 µs 556.4 µs 3.21x
dumps(twitter, sort_keys=True) 1,289.1 µs 428.4 µs 3.01x
dumpb(citm, OPT_SORT_KEYS) 1,075.7 µs 440.0 µs 2.44x
dumpb(twitter, OPT_SORT_KEYS) 615.8 µs 396.8 µs 1.55x
decompress(1KB zstd / gzip) 1.0 / 2.1 µs 0.3 / 0.7 µs 3.3x / 3.0x
loads(1KB zstd / gzip) (vs 3.5 µs plain) 4.6 / 5.6 µs 3.7 / 4.1 µs 1.24x / 1.37x
Typed 30-field + 20-unknown dataclass (1,000 recs) 3,325.9 µs 1,685.9 µs 1.97x
Typed List[RecSlots] (2,000 recs) 881.9 µs 689.3 µs 1.28x
Typed List[int] (50K ints) 1,142.4 µs 961.9 µs 1.19x
bench_typed.py (twitter / citm) 2,179 / 860 MB/s 2,291 / 892 MB/s +5.1% / +3.7%
loads_many fields= (20K docs / 5K comma docs) 2,714 / 1,062 µs 2,549 / 990 µs +6.5% / +7.2%

Core bench.py (loads) shows zero regressions across all corpus files.

Verification

  • pytest tests with simdjson-data: 1,222 passed (including new tests in test_lazy.py, test_dumps.py, test_typed.py, and test_compressed.py covering duplicate keys, concurrent index races, negative-step slicing, SIMD wide-string boundaries and lone surrogates, shared key-cache \x7f/Unicode isolation, dict subclasses, slotted/wide dataclasses, Enum/Literal/typed container validation, compressed fallbacks, empty/skippable frames, and re-entrancy).
  • tests/test_stubs.py (mypy.stubtest + mypy --strict) passed.
  • Compiled with 0 warnings (-Wall -Wsign-compare -Wunreachable-code).
  • 500-cycle tracemalloc stress test across all new code paths (including error paths) showed a 32-byte net delta.
  • Audited for x86-64 (pure SSE2), ARM64 (NEON), Pyodide (32-bit scalar, no threads), MSVC, CPython 3.10–3.15, and free-threaded (Py_GIL_DISABLED) builds.

…nd fields=

Performance optimizations across five subsystems without modifying vendored libraries or changing behavior:

- Lazy Object/Array views: lock-free lazily published ObjectIndex (open-addressed hash table preserving first-key-wins semantics on >=16-key objects) and strided ArrayIndex (on >=32-element arrays), single-pass O(N) array slicing (including negative steps), and compact-ASCII object lookup fast path.
- dumps/dump/dumpb: METH_FASTCALL for dumps, stack-allocated cycle path, exact-type inline dispatch, GIL borrowed mode with safe restart, shared EncodedKey cache (with ensure_ascii_ok isolation), NEON/SSE2/scalar SIMD ASCII-escape scanners for wide strings, fast C++ sort_keys for dumps, and arena-backed OrjsonEncoder dict sorting with std::sort.
- Typed decoding: O(1) field hash table + length mask, direct slot writes for slotted dataclasses, tp_alloc fast path, zero-allocation Enum/Literal lookup tables, and specialized loops for List[int|float|str|bool] and Dict[str, str|int].
- Compressed input: thread-local libdeflate/ZSTD_DCtx/scratch cache (freed by release() and thread exit), single-frame known-size zstd fast path, zero-PyBytesObject RawOutput decompression in with_input_f, and max_size=0 fix in gunzip.
- Streams/fields= and minify: single-pass extract_dom_walk, bitmask tracking in od_walk, and avoid shrinking copy in minify when output >= 50% of input.
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