Skip to content

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

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

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

@gaborbernat gaborbernat commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

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.
@github-actions

github-actions Bot commented Sep 5, 2026

Copy link
Copy Markdown

This PR is stale because it has been open for 90 days with no activity.

@github-actions github-actions Bot added the stale Stale PR or inactive for long period of time. label Sep 5, 2026
@gaborbernat

Copy link
Copy Markdown
Contributor Author

@picnixz any appetite to get this merged or should we close it? Thanks!

@picnixz

picnixz commented Sep 8, 2026

Copy link
Copy Markdown
Member

I don't think it's really worth it. We are already fast for tiny strings and the code is a bit more complex to read IMO.

@gaborbernat gaborbernat closed this Sep 8, 2026
@gaborbernat

Copy link
Copy Markdown
Contributor Author

Considering that JSON is the de facto standard widely used in coding for all web servers, I think even small wins can be very worthwhile. But if there is no appetite for it, that’s fine too.

@picnixz

picnixz commented Sep 8, 2026

Copy link
Copy Markdown
Member

I wasn't really against, but your arument about web is legitimate. However, how about using WHITESPACE_STR directly? if @serhiy-storchaka or @vstinner think it's worth it we can consider it

@serhiy-storchaka

Copy link
Copy Markdown
Member

Right now I am working on new JSON parser which may replace the current one. So, such micro-optimizations are premature.

@gaborbernat gaborbernat reopened this Sep 8, 2026
@gaborbernat gaborbernat closed this Sep 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review stale Stale PR or inactive for long period of time.

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

3 participants