Skip to content

gh-150860: Skip the whitespace scan in json.loads() when there is none#150861

Open
gaborbernat wants to merge 1 commit into
python:mainfrom
gaborbernat:opt/json-decode-skip-ws
Open

gh-150860: Skip the whitespace scan in json.loads() when there is none#150861
gaborbernat wants to merge 1 commit into
python:mainfrom
gaborbernat:opt/json-decode-skip-ws

Conversation

@gaborbernat
Copy link
Copy Markdown
Contributor

@gaborbernat gaborbernat commented Jun 3, 2026

Decoding with json.loads() runs a whitespace-skipping regular expression at both ends of the document through the pure-Python decode() wrapper, on every call, before and after the C scanner does the real work. Almost all documents have no surrounding whitespace, so both matches scan nothing yet still pay for the call and a match-object allocation. For the small documents that dominate real traffic, that fixed overhead is a meaningful slice of the decode time.

This skips the leading match when the document does not start with whitespace, and the trailing match when the parse already consumed the whole string. Documents that do have surrounding whitespace keep the original behavior, output is unchanged, and the wrapper stays in Python so the win applies to the default C-accelerated build.

The effect is concentrated on small, whitespace-free documents (the common case). It costs a little on the rare document padded with both leading and trailing whitespace (one extra branch), and is neutral on large documents:

Benchmark base patched
loads tiny, no whitespace 469 ns 297 ns: 1.58x faster
loads tiny, leading whitespace 473 ns 392 ns: 1.21x faster
loads tiny, trailing whitespace 463 ns 400 ns: 1.16x faster
loads tiny, both leading + trailing 473 ns 518 ns: 1.09x slower
loads 4 KB / 32 KB / 100 KB, no whitespace within noise (±2–3%)

The large-document deltas sit inside run-to-run noise: the change only adds or removes work at the document boundaries, so it cannot scale with document size. A constant-overhead change measuring as a size-proportional regression is the signature of measurement noise on a contended machine, not a real cost.

This overlaps with the broader rewrite in gh-117397 and is filed separately so the small, self-contained version can be judged on its own. It was split out of #150827, which now carries only the encoder change.

Benchmark (pyperf)

Run base vs patched by swapping Lib/json/decoder.py on the same interpreter.

import json, pyperf
def sized(target):
    n = target // 12
    while True:
        s = json.dumps({str(i): i for i in range(n)})
        if len(s) >= target: return s
        n += target // 24
PAYLOADS = {
    "no_ws_tiny": '{"a":1}', "leading_ws": '  {"a":1}', "trailing_ws": '{"a":1}  ',
    "both_ws": '  {"a":1}  ', "no_ws_4kb": sized(4*1024),
    "no_ws_32kb": sized(32*1024), "no_ws_100kb": sized(100*1024),
}
runner = pyperf.Runner()
for name, payload in PAYLOADS.items():
    runner.timeit(name=f"json_loads/{name}", stmt="loads(s)",
                  setup=f"from json import loads; s = {payload!r}")

Resolves #150860.

…is none

decode() ran a whitespace-skipping regex at both ends of every document
even though most have none. Skip the leading match when the document does
not start with whitespace and the trailing match when the parse already
consumed the whole string. Documents with surrounding whitespace keep the
original behavior and output is unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Avoid redundant whitespace scan in json.loads() for documents without surrounding whitespace

1 participant