Repository navigation
Conversation
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR optimizes several hot paths across
fastsimdjsonwithout modifying vendored libraries or changing public behavior or parity withjson,orjson, andmsgspec:Lazy
Object/Arrayviews (src/fastsimdjson.cpp)std::atomic<void*>) open-addressed hash indices for repeated key lookups onObjectviews (>= 16keys, preserving first-key-wins semantics for duplicate keys) and strided tape-offset indices for backward/random access onArrayviews (>= 32elements).O(N)array_subscriptslicing for both positive and negative steps, reusing a singleBuilder.object_lookup.Serialization (
dumps,dump,dumpbinsrc/fastsimdjson.cpp)METH_FASTCALL | METH_KEYWORDSfordumps, stack-allocated cycle path, exact-type inline dispatch (PyUnstable_Long_IsCompacton 3.12+), fast separator modes, and GILborrowedmode (with safe restart if a dict subclass or non-str key comparison runs Python code).EncodedKeycache acrossdumps/dump/dumpb(guarded byensure_ascii_okso\x7fand non-ASCII keys remain isolated betweenensure_ascii=Trueand UTF-8 modes).ensure_ascii=True, plus aHEX_PAIRSlookup table.encode_dict_sorted_strfordumps(..., sort_keys=True)and arena-backedOrjsonEncoder::encode_dict_collectedwithstd::sortfor string keys.Typed decoding (
src/typed.h)field_table+ 64-bit length bitmask forO(1)field lookup and unknown-key rejection.PyMemberDescrObjectslot writes (guarded byPy_IS_TYPE(out, tp)) for@dataclass(slots=True)andtp_allocfast path for non-abstractobject.__new__dataclasses.EnumandLiteralvalues.List[int|float|str|bool]andDict[str, str|int]onTapeSource; presizedTypedDict.Compressed input (
src/compressed.h,src/fastsimdjson.cpp)ThreadCachereusinglibdeflate_decompressor,ZSTD_DCtx, and a padded scratch buffer (<= 4 MiB, freed byrelease()and thread exit).unzstdfast path avoidingFramevector and thread setup.PyBytesObjectdecompression intoRawOutputinsidewith_input_f(re-entrant via scratch ownership transfer, lazily wrapping intoPyBytesonly onjson.loadsfallback).gunzipinitial reservation whenmax_size=0on empty gzip payloads.Streams /
fields=&minify(src/fastsimdjson.cpp)extract_dom_walkover the compiledFieldNodetree and bitmask tracking inod_walk._PyBytes_Resizecopy inminifywhen 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)dumpsgeometric mean vsjson.dumpsimproves from 5.38x → 8.44x (+57%):json.dumpsdumpsbeforedumpsafterdumpbafterorjsontwitter.jsongsoc-2018.jsoncitm_catalog.jsongithub_events.jsonmesh.jsoncanada.jsonSubsystem highlights
Array[::-1](10,000 elements)Array[::-3](10,000 elements)Array[rand]×1,000 (10,000 elements)Object[k]×1,000 (2,000-key object)citm["events"][k](all 184 keys)dumpsLatin-1 32K mostly-ASCII (ensure_ascii=True)dumpsUCS-2 32K mostly-ASCII (ensure_ascii=True)dumpsUCS-4 32K mostly-ASCII (ensure_ascii=True)dumpsUCS-4 16K all-emoji (ensure_ascii=True)dumps(citm, sort_keys=True)dumps(twitter, sort_keys=True)dumpb(citm, OPT_SORT_KEYS)dumpb(twitter, OPT_SORT_KEYS)decompress(1KB zstd / gzip)loads(1KB zstd / gzip)(vs 3.5 µs plain)List[RecSlots](2,000 recs)List[int](50K ints)bench_typed.py(twitter/citm)loads_manyfields=(20K docs / 5K comma docs)Core
bench.py(loads) shows zero regressions across all corpus files.Verification
pytest testswithsimdjson-data: 1,222 passed (including new tests intest_lazy.py,test_dumps.py,test_typed.py, andtest_compressed.pycovering 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.-Wall -Wsign-compare -Wunreachable-code).tracemallocstress test across all new code paths (including error paths) showed a 32-byte net delta.Py_GIL_DISABLED) builds.