Repository navigation
Drop two module state lookups that were already answered - #1536
Conversation
MultiDict.__init__() and CIMultiDict.__init__() resolved the module state from the type with PyType_GetModuleByDef() and PyModule_GetState(), although tp_new() had already stored that same pointer in self->state before either of them ran. Read the field instead. The istr object carried a mod_state pointer of its own, written on every creation and never read anywhere; the only field read off an istr is canonical. Drop it, which also takes eight bytes off every istr.
Merging this PR will improve performance by 11.13%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_create_multidict_with_dict[ci-c] |
99.4 µs | 89.4 µs | +11.13% |
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:claude/drop-answered-state-lookups (8a19265) with master (fdceefa)
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1536 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 40 40
Lines 6820 6823 +3
Branches 596 596
=========================================
+ Hits 6820 6823 +3
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:
|
|
aio-libs#1536 removed the mod_state pointer from istrobject, which this branch's rewrite of istr_new() had carried into _istr_finish(). Dropped that store there too; the rest of the merge is clean.
<!-- Thank you for your contribution! --> ## What do these changes do? `istr(x)` went through `type_call()`, which packs the argument into a tuple, and `istr_new()` then unpacked it again with `PyArg_ParseTupleAndKeywords()`. The one-argument form, which is how an `istr` gets built in practice, needs none of that. `istr` now has a `tp_vectorcall` that handles that form directly, and leaves `istr()` and the `encoding` / `errors` signature to a cold path that rebuilds the tuple and calls `istr_new()` as before. Subclasses are unaffected: CPython does not copy `tp_vectorcall` to a subclass, so `class Sub(istr)` still goes through `type_call()` and `tp_new`. There is one cost, and it is not in the `istr` path. `getall()` runs nine more instructions per call, because the added code moves where the compiler draws its inlining line and `md_calc_identity()` lands out of line in `_md_get_all_locked()`. The multidict side of the callgrind profile is otherwise identical, and no attempt to place the new code differently moved that number. C-extension-only. The pure-Python `istr` is a plain `str` subclass with no constructor of its own, so there is nothing to mirror there. ## Are there changes in behavior for the user? No. Every constructor form was compared against `master` case by case, including the `encoding` and `errors` arguments, the keyword forms, the error messages for bad arguments, subclasses, `copy` and `pickle`; the output is identical. ## Is it a substantial burden for the maintainers to support this? No. ## Related issue number N/A ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [x] Documentation reflects the changes <!-- N/A, no user-visible API change --> - [ ] 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` `master` was merged in after #1536 landed: that PR removed the `mod_state` pointer from `istrobject`, which this branch's rewrite of `istr_new()` had carried into `_istr_finish()`. The numbers above were re-measured on the merged result. Drafted with Claude Opus 5 via Claude Code; reviewed by @asvetlov. <details> <summary>Agent run details (optional, for reviewers)</summary> Measured with callgrind, instructions retired per operation, `PYTHONHASHSEED=0`, GC collected then disabled, each case run at N and 2N iterations with the totals subtracted so startup and loop overhead cancel. Base and branch built and measured back to back in one session, with the base at 88026da. CPython 3.14.7, GIL build, GCC 15.2. | benchmark | base | new | delta | | --- | ---: | ---: | ---: | | `istr('Content-Type')` | 2599.9 | 2105.9 | -494 (-19.0%) | | `istr('content-type')` | 2599.9 | 2105.9 | -494 (-19.0%) | | `istr(an_istr)` | 1105.9 | 353.9 | -752 (-68.0%) | | `CIMultiDict.getall` | 1359.0 | 1368.0 | +9 (+0.7%) | | `CIMultiDict(dict)` | 4104.9 | 4104.9 | 0 | | `CIMultiDict(dict)`, mixed-case keys | 9077.9 | 9077.9 | 0 | | `MultiDict(dict)` | 3117.9 | 3117.9 | 0 | | `CIMultiDict()` | 955.9 | 955.9 | 0 | | `MultiDict` subclass from a dict | 3937.9 | 3937.9 | 0 | | `CIMultiDict` subclass from a dict | 4801.9 | 4801.9 | 0 | | `CIMultiDict.__getitem__` (str key) | 346.9 | 346.9 | 0 | | `CIMultiDict.__getitem__` (istr key) | 327.9 | 327.9 | 0 | | `CIMultiDict.__getitem__` (mixed-case key) | 944.9 | 944.9 | 0 | | `MultiDict.__getitem__` | 268.9 | 268.9 | 0 | | `MultiDict.__contains__` | 251.9 | 251.9 | 0 | On the `getall` regression: a function-level callgrind diff shows the cost moving from `identity.h:_md_get_all_locked` to a now separate `md_calc_identity.isra.0`, which is the call overhead. `NOINLINE` on each of the new helpers, and on `istr_new` itself, was tried; every variant still reads 1368. Marking `md_calc_identity()` `ALWAYS_INLINE` does fix it (1351) and speeds construction up by 3% to 4%, but costs 2.6% on `CIMultiDict.__getitem__` and 4.6% on the `istr`-key form, so it does not belong here. Tests, CPython 3.14.7: ``` pytest -q 2353 passed, 98 skipped MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions 1132 passed, 8 skipped pytest -q -m hypothesis 142 passed, 5 skipped ASan + UBSan, PYTHONMALLOC=malloc, -k "not test_leak" 2342 passed, 98 skipped make doc-spelling build succeeded PYENV_VERSION=3.13.2 pre-commit run --all-files all passed ``` </details>
What do these changes do?
Two places in the C extension asked for the module state although it was
already at hand.
MultiDict.__init__()andCIMultiDict.__init__()calledget_mod_state_by_def(), which isPyType_GetModuleByDef()plusPyModule_GetState(), even thoughtp_new()stores that same pointer inself->statebefore either of them can run. They read the field now. Thetwo proxy
tp_init()s are left alone:MultiDictProxy'stp_newisPyType_GenericNew, soself->mdis stillNULLthere and the lookup isthe only way to get the state.
The
istrobject had amod_state *field that was written on everycreation and never read; the only field ever read off an
istriscanonical. Dropping it also takes eight bytes off everyistr.This is C-extension-only. The pure-Python backend has no module state, so
there is nothing to mirror there.
Are there changes in behavior for the user?
No.
Is it a substantial burden for the maintainers to support this?
No, it removes code.
Related issue number
N/A
Checklist
CONTRIBUTORS.txtCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtDrafted with Claude Opus 5 via Claude Code; reviewed by @asvetlov.
Agent run details (optional, for reviewers)
Measured with callgrind, instructions retired per operation,
PYTHONHASHSEED=0,GC collected then disabled, each case run at N and 2N iterations with the totals
subtracted so startup and loop overhead cancel. CPython 3.14.7, GIL build.
MultiDictsubclass from a 10-key dictCIMultiDictsubclass from a 10-key dictistr('Content-Type')CIMultiDict(dict)MultiDict(dict)CIMultiDict.__getitem__(str key)CIMultiDict.__getitem__(istr key)MultiDict.__getitem__CIMultiDict.getallThe 43 instructions are the
PyType_GetModuleByDef()andPyModule_GetState()call pair. Only the subclass path reachestp_init():a call on the exact type goes through
tp_vectorcall, and CPython does notcopy
tp_vectorcallto a Python subclass, so those fall back totype_call()->tp_new+tp_init.istr.__basicsize__goes from 80 to 72.Tests, CPython 3.14.7: