Repository navigation
Speed up the argument binding of the C extension - #1549
Conversation
multidict_get() materialised the implicit None on every call, then carried a decref_default flag to release it again, even though the default is only reachable when the key is absent. Do the lookup directly and produce the constant on the miss path, where it is the return value. Callgrind, 200k calls: md.get(key) on a present key drops 1.19%, and md.get(key, None) 0.20%. The saving is not only Py_GetConstant(): the flag, its branch and the Py_CLEAR() go with it. setdefault() keeps the old shape; it has to hand the default to md_set_default() inside the critical section, so there is no miss path to defer the constant to.
Two changes to how FASTCALL arguments are bound.
parse2() compiled to a single outlined clone shared by all eleven call
sites, so md.get(key) paid a call into the keyword machinery it never
used. Guard the all-positional case in the inline wrapper and leave the
rest to a COLD parse2_slow(); the wrapper now costs five instructions at
the call site. While the keyword walk is out of line anyway, take the
tuple through PyTuple_GET_SIZE()/PyTuple_GET_ITEM(): all eleven methods
are METH_FASTCALL|METH_KEYWORDS, so kwnames is a tuple or NULL and the
error branches of the checked calls were unreachable.
The names are now compared by identity first. Both sides are interned,
the parameter names in the module state and the keyword names the
compiler puts in kwnames, so a call written as get(key=k) settles on a
pointer compare instead of memcmp(), which was 45% of the keyword path.
Names that never reach the intern table, as built by get(**{"key": k}),
still need the comparison, so it stays as a fallback; this mirrors
find_keyword() in CPython's Python/getargs.c.
2b5e94c to
fb8541a
Compare
Merging this PR will improve performance by 9.06%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_multidict_get_miss[cs-c] |
78.3 µs | 71.8 µs | +9.06% |
Tip
Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.
Comparing asvetlov:parse2-fast-binding (fb8541a) with master (9682ba1)
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1549 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 40 40
Lines 6876 6890 +14
Branches 596 596
=========================================
+ Hits 6876 6890 +14
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Takes master's copies of hashtable.h, atomic_helpers.h and the 1546 fragment: aio-libs#1546 landed there, so the copies this branch carried are redundant and master's also has aio-libs#1539, aio-libs#1549 and aio-libs#1550 on top.
aio-libs#1539, aio-libs#1549 and aio-libs#1550 landed since these were collected, and the add row moved most: 876 to 765 on the GIL build, 1,035 to 939 free-threaded. Also restore the note that d.add() starts from an empty mapping and inserts 200 keys. Without it the lead-in describes every row as running against a 200-key mapping, which is true of the other two but not of that one.
…1553) <!-- Thank you for your contribution! --> ## What do these changes do? `setdefault()` called without an explicit default built the implicit `None` on every call, then carried a flag to release it again, although only the call that actually inserts consumes it. `md_set_default()` now reads a `NULL` *value* as `None`, so the method simply forwards what it parsed and the flag, its branch and the `Py_CLEAR()` all go away. The constant lives in the module state rather than coming from `Py_GetConstant()` at the point of use, because the substitution happens just before the critical section is taken. On 3.13+ either would do; on 3.10 to 3.12 the `pythoncapi_compat` shim initialises its table lazily and calls `PyLong_FromLong()`, so a first call landing under the lock could collect. Instruction counts against `cd92a6c`, callgrind, 200k calls: | case | master | this branch | | | --- | --- | --- | --- | | `d.setdefault(key)`, present key | 491,825,979 | 486,878,820 | -1.01% | | `d.setdefault(key, default)`, present key | 494,626,107 | 493,681,201 | -0.19% | | `d.setdefault(key)`, inserting | 290,700,236 | 290,812,020 | +0.04% | The inserting call is unchanged, as expected: it still stores the same constant, just one that was not built for the occasion. Only the C extension is touched; the pure-Python implementation is unchanged. ## Are there changes in behavior for the user? Not at the Python level; `setdefault()` returns and stores exactly what it did before. The public C API gains a little: `MultiDict_SetDefault()` forwards straight to `md_set_default()`, so it now accepts `NULL` for *default_value* and reads it as `None`, where the documentation previously called the argument required. `docs/capi.rst` says so, and both `_testcapi.c` and `_testcyapi.pyx` exercise it. `MultiDict_CAPI_VERSION` stays at 1 deliberately. It exists to stop a client built against a newer header from running on an older runtime, and version 1 has not shipped: the capsule landed after v6.9.1, so there is no released runtime that would reject a `NULL` default. Bumping would announce a boundary no client can be on the wrong side of. The Cython wrapper cannot express a `NULL` object, but passing `None` is read identically, so `default_value` just gained a `None` default, which incidentally makes its signature match the Python method. ## Is it a substantial burden for the maintainers to support this? No. It removes a local variable and a branch from the method, adds one field to the module state next to the interned names already there, and leaves `md_set_default()`'s behaviour for a non-`NULL` default untouched. ## Related issue number None. Follow-up to #1549, which did the same for `get()`. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` - N/A, no such file in this repo - [x] Add a new news fragment into the `CHANGES/` folder - [x] `make doc-spelling` passes and any new technical words are added to `docs/spelling_wordlist.txt` Drafted with Claude Code (Opus 5); reviewed by @asvetlov. <details> <summary>Agent run details (optional, for reviewers)</summary> Both legs ran in their own venv, and the pure-Python leg in its own tree copy, so neither picked up a stale `.so`. The C leg ran with `MULTIDICT_TEST_REQUIRE_CYAPI=1` after building Cython, so the `_testcyapi` half of `test_capi.py` was a hard requirement rather than a skip. ``` C extension: MULTIDICT_TEST_REQUIRE_CYAPI=1 pytest tests -q 2691 passed, 33 skipped pure Python: MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions 1264 passed, 11 skipped, 1268 deselected lint: pre-commit run --all-files all hooks passed docs: make doc-spelling build succeeded ``` Two tests cover the new `NULL` path through both harnesses, one inserting and one finding an existing key. The Python-level paths were already covered by `test_mutable_multidict.py`, which asserts `setdefault("key") == "one"` and `setdefault("noexist") is None`. Measurement notes: callgrind, `PYTHONHASHSEED=0`, warm `__pycache__`, 200k iterations, rebuilt from the same tree for each side. Cross-rebuild noise on this harness measures at about 0.01%, which is what the inserting row is showing. </details>
<!-- Thank you for your contribution! --> ## What do these changes do? The `istr` section already tells people to build their keys once and reuse them, but not what that buys. This adds the instruction counts, for both builds, next to the plain `str` equivalents, and points out that a key which is not already lower case saves more still, since it has to be copied into a lower-cased string whose hash is not cached. Numbers come from `benchmarks/callgrind_driver.py --include-multidict-only`, the same harness and machine as the tables in `docs/benchmark.rst`. #1546 has landed, so this is down to its own two files. The figures were re-measured against master afterwards, since #1539, #1549 and #1550 also moved them; `d.add()` shifted most, 876 to 765 on the GIL build. ## Are there changes in behavior for the user? No, documentation only. ## Is it a substantial burden for the maintainers to support this? No, though the table joins `docs/benchmark.rst` in needing a refresh when the figures move. ## Related issue number None. ## Checklist - [x] I think the code is well written — N/A, documentation only - [ ] Unit tests for the changes exist — N/A - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` — N/A - [x] Add a new news fragment into the `CHANGES/` folder - [x] `make doc-spelling` passes and any new technical words are added to `docs/spelling_wordlist.txt` Drafted with Claude Opus 5 in Claude Code; reviewed by @asvetlov. --------- Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
What do these changes do?
Three changes to the argument handling of the C extension, no behaviour
change in any of them.
parse2()compiled to a single outlined clone shared by all eleven callsites and was inlined nowhere, so
md.get(key)paid a call into thekeyword machinery it never used. The all-positional case now binds in
the inline wrapper, five instructions at the call site, and the rest
moved to a
COLD parse2_slow(). Since the keyword walk is out of lineanyway, it takes the tuple through
PyTuple_GET_SIZE()andPyTuple_GET_ITEM(); all eleven methods areMETH_FASTCALL | METH_KEYWORDS, sokwnamesis a tuple orNULLandthe error branches of the checked calls were unreachable.
Parameter names are now interned in the module state and matched against
kwnamesby identity before falling back to a comparison, which is whatfind_keyword()in CPython'sPython/getargs.cdoes. A call written asget(key=k)settles on a pointer compare; thememcmp()it replaces was45% of the keyword path. The fallback is not optional:
get(**{"key": k})builds names that never reach the intern table, and there is a test for
exactly that.
Finally,
multidict_get()built the implicitNonedefault on everycall and carried a flag to release it again, although it is only
reachable when the key is absent. It now does the lookup directly and
produces the constant on the miss path, where it is the return value.
setdefault()keeps the old shape, since it has to hand the default tomd_set_default()inside the critical section.Instruction counts against
9682ba1, callgrind, 200k calls:md.get(key)md.get(key, default=None)md.getone(key=key)md.get(key, None)md.getone(key)md.getall(key)md.add(key, value)Only the C extension is touched; the pure-Python implementation is
unchanged.
Are there changes in behavior for the user?
No. The same calls succeed, the same ones raise, and the messages are
identical. A behaviour matrix of 27 argument combinations compared
against the pure-Python backend is unchanged by this branch.
Is it a substantial burden for the maintainers to support this?
No, though two of the assumptions are worth knowing about. The tuple
macros rely on every
parse2()caller stayingMETH_FASTCALL | METH_KEYWORDS, and the identity match relies on themodule state holding interned names, so
PyUnicode_InternFromString()there is load bearing rather than incidental.
Related issue number
None. Follow-up to #1545.
Checklist
CONTRIBUTORS.txt- N/A, no such file in this repoCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtDrafted with Claude Code (Opus 5); reviewed by @asvetlov.
Agent run details (optional, for reviewers)
Both legs ran in their own venv, and the pure-Python leg in its own tree
copy, so neither picked up a stale
.so.Measurement notes: callgrind,
PYTHONHASHSEED=0, warm__pycache__,200k iterations. Cross-rebuild noise was measured at about 0.01% by
building identical source twice and comparing, so the deltas above are
well clear of it.
One rejected variant, recorded so it is not retried: screening the name
comparison with an inline first-character check before
PyUnicode_CompareWithASCIIString()regressed the keyword paths by 0.5to 0.8%. The common keyword forms hit on the first name tried, so there
is no
memcmp()to skip and the screen is pure overhead. Identitymatching was the change that actually paid.