gh-150860: Skip the whitespace scan in json.loads() when there is none - #150861
gh-150860: Skip the whitespace scan in json.loads() when there is none#150861gaborbernat wants to merge 1 commit into
Conversation
…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.
|
This PR is stale because it has been open for 90 days with no activity. |
|
@picnixz any appetite to get this merged or should we close it? Thanks! |
|
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. |
|
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. |
|
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 |
|
Right now I am working on new JSON parser which may replace the current one. So, such micro-optimizations are premature. |
Decoding with
json.loads()runs a whitespace-skipping regular expression at both ends of the document through the pure-Pythondecode()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:
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.pyon the same interpreter.Resolves #150860.