Repository navigation
Add CIMultiDict benchmarks for plain str keys - #1521
Merged
Merged
Conversation
Every existing CIMultiDict benchmark uses istr keys, which serve the identity from the cached canonical form, or digit-only str keys, which are already lowercase. Neither shape exercises the lowering that a mixed-case plain str key has to go through on every operation.
Merging this PR will not alter performance
Performance Changes
Comparing |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1521 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 38 38
Lines 6406 6455 +49
Branches 579 591 +12
=========================================
+ Hits 6406 6455 +49
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:
|
asvetlov
marked this pull request as ready for review
September 22, 2026 22:38
Contributor
|
5 of 6 tasks
asvetlov
added a commit
that referenced
this pull request
Sep 23, 2026
<!-- Thank you for your contribution! --> ## What do these changes do? `_ci_key_to_identity()` called `str.lower()` on every plain `str` key, so a `CIMultiDict` paid an attribute lookup, a vectorcall, a string allocation and a from-scratch hash on every single lookup, insert and delete. For an ASCII string CPython's `str.lower()` is `PyUnicode_New(len, 127)` filled by `Py_TOLOWER()` per byte, and it has no shortcut for a string that is already lowercase, so even `d["content-type"]` allocated and rehashed a copy. An exact `str` that is ASCII is now handled directly. The key is scanned for an uppercase byte, eight at a time, and if it has none it already is its own identity, so it is reused as is: no copy, and `_unicode_hash()` finds the key's cached `ob_shash` instead of hashing a fresh string. A key that does have uppercase is lowered straight into a new string, still without the method call. The gate is deliberately `PyUnicode_CheckExact`. A `str` subclass may override `lower()`, and the identity of a subclass instance has to keep coming from the override; `tests/test_mutable_multidict.py` and `tests/test_multidict.py` already depend on that, and there is a new test that pins it. `istr`, `str` subclasses and non-ASCII keys all take the path they took before. Everything below the `istr` check now sits behind a `noinline` call, and `compiler.h` gains a `NOINLINE` macro alongside `COLD` and `ALWAYS_INLINE` for it. This is load-bearing, not cosmetic. `md_calc_identity()` is inlined into every `md_*()` that takes a key, so it carries `_ci_key_to_identity()` with it, and growing that function pushed `md_contains()` and `md_next()` past the inliner's budget at their own call sites. The cost landed on code the fast path cannot help: `keys().isdisjoint()` took 31% more instructions on a plain `MultiDict`, whose keys never reach the case-insensitive branch at all. Behind the call, `_ci_key_to_identity()` is smaller than it was before this change and the effect is gone. `multidict/_multidict_py.py` is not touched. The dual-backend rule applies, but there is nothing to mirror: the pure Python `_CIMixin._identity()` already is `key.lower()`, and no pure-Python spelling of the same idea is cheaper than the method call it would replace. Instruction counts, callgrind `I refs` with `PYTHONHASHSEED` pinned and interpreter startup cancelled by differencing two loop lengths: | case | master | head | change | | --- | --- | --- | --- | | lookup, lowercase key | 156.5M | 83.5M | -46.6% | | lookup, mixed-case key | 156.5M | 129.6M | -17.2% | | `getall()` by `istr` (control) | 17.23M | 16.93M | -1.7% | | lookup by `istr` (control) | 78.7M | 77.4M | -1.6% | | `MultiDict` lookup (control) | 78.6M | 77.7M | -1.1% | | `MultiDict` `keys().isdisjoint()` (control) | 71.0M | 72.2M | +1.8% | CodSpeed, against the benchmarks #1521 added: 41 improvements, 269 unchanged, no regressions. | benchmark | base | head | change | | --- | --- | --- | --- | | `cimultidict_fetch_str_lower_case[c]` | 1945.6 us | 615.3 us | x3.2 | | `cimultidict_insert_str_lower_case[c]` | 36.4 ms | 15.7 ms | x2.3 | | `cimultidict_fetch_str_mixed_case[c]` | 2 ms | 1.4 ms | +35% | | `cimultidict_insert_str_mixed_case[c]` | 36.4 ms | 29.9 ms | +22% | | `cimultidict_add_str_mixed_case[c]` | 40.7 ms | 34 ms | +20% | The existing `[ci-c]` benchmarks move too, since their keys are digits and so already lowercase: `multidict_extend_str` x3.3, `create_multidict_with_many_items` x2.8, `multidict_setitem_str` +95%, `multidict_delitem_str` +93%, and so on. An earlier push, before the last commit, reported four regressions of about -11%, on `keys_view_is_disjoint[cs-c]` and `[ci-c]` and on `cimultidict_getall_istr_hit` and its many-values variant. Those were the inliner-budget effect above rather than runner noise, and all four are back to unchanged now. The report did carry an environment difference that listed them, but a master-to-master comparison across the same CPU swap reports them unchanged, so it never explained them. Fixing it also moved `getall_str_hit[ci-c]` from +12% to +20% and `getall_str_hit_large_table[ci-c]` from +10% to +15%. Left out on purpose: `istr_new()` also calls `lower()`, but `canonical` has to be an exact `str` while the object being lowered is the `istr`, so the reuse-the-key half is unavailable there and only the dispatch could be saved, once per `istr`, on the one type that already caches its identity. ## Are there changes in behavior for the user? No. Identities are internal and are compared by content, never by pointer, and the C extension keeps producing exactly what `str.lower()` produced. ## Is it a substantial burden for the maintainers to support this? No, it is one self-contained fast path in `identity.h` with no new state and no new locking; it runs no Python code, so unlike the call it replaces it cannot suspend a critical section. ## 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 change - [ ] 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` Rebased on top of #1521, which added the CodSpeed benchmarks this change is meant to move, so the report here compares against a baseline that has them. Drafted with Claude Code (Claude Opus 5); reviewed by @asvetlov. <details> <summary>Agent run details (optional, for reviewers)</summary> **Tests**, full suite, all green: | leg | result | | --- | --- | | CPython 3.13.12, C extension | 2243 passed | | CPython 3.13.12, `--no-c-extensions` | 1120 passed | | CPython 3.13.12, `-m hypothesis` | 142 passed | | CPython 3.13.12, `MULTIDICT_DEBUG_BUILD=1` | 2243 passed | | CPython 3.13.12, ASan + UBSan | 2232 passed, clean | | CPython 3.13.12, ASan + UBSan, `-m hypothesis` | 142 passed, clean | | CPython 3.10.17 | 2243 passed | | CPython 3.14.7t, free-threaded | 2232 passed | | CPython 3.14.7t, free-threaded, `-m hypothesis` | 143 passed | | CPython 3.15.0rc2 | 2243 passed | **Lint**: `pre-commit run` over the touched files, passed. `make doc-spelling`, build succeeded. **Mutation checks**, to show the new tests are load-bearing: | mutation | caught by | | --- | --- | | `PyUnicode_CheckExact` relaxed to `PyUnicode_Check` | `test_str_subclass_lower_override_is_used`, plus the pre-existing `Hack` test | | `Py_TOLOWER()` replaced with an unconditional `\| 0x20` | `test_ascii_identity_matches_str_lower` | | word-loop bound `'A'` off by one | `test_ascii_identity_matches_str_lower` | | word-loop bound `'Z'` off by one | `test_ascii_identity_matches_str_lower` | | final overlapping word dropped | `test_ascii_identity_matches_str_lower` | | final overlapping word shifted by one | `test_ascii_identity_matches_str_lower` | | word loop allowed to read a word past the end | ASan, `heap-buffer-overflow`, `READ of size 8` in `_ascii_has_upper` | That last one is why a key shorter than one word takes a byte loop and the final word ends at the key's end rather than starting past it: a compact ASCII `str` is allocated as its header plus `len + 1` bytes, so a word read past either end leaves the block. **How the inlining regression was found and fixed.** CodSpeed flagged the four benchmarks above; the four were reproduced locally under callgrind, and the profile showed the cause directly. On master `md_contains()` and `md_next()` are inlined into `multidict_keysview_isdisjoint()`; with the fast path inlined they appear as out-of-line `md_contains.part.0.constprop.0` and `md_next`, with `htkeysiter_init()` split out too. Three shapes were then measured, as instructions per `keys().isdisjoint()` over 100 keys on a plain `MultiDict`: | shape | instructions | vs master | | --- | --- | --- | | master | 17,737 | | | fast path inlined | 23,299 | +31.4% | | scan helpers left to the compiler's judgement | 23,299 | +31.4% | | whole ASCII arm behind a `noinline` call | 18,577 | +4.7% | | everything below the `istr` check behind it | 18,055 | +1.8% | The last shape is what is committed. Dropping `ALWAYS_INLINE` from the scan helpers changes nothing, because the helpers are not what crosses the budget; the size of `_ci_key_to_identity()` as a whole is. **Portability of the word scan**, since CI builds and tests s390x (big endian), ppc64le, riscv64, armv7l, i686 and win32: - *Byte order* does not matter, because the word test asks only whether some lane is uppercase, never which one. A standalone harness ran the shipped word test with the word assembled both little and big endian and compared both against a byte-at-a-time reference: 6,590,930 checks, 0 failures. It covers every ASCII value in every lane against twelve adversarial fillers (including `@`, `[`, `` ` ``, `{`, `\x7f`), every pair of ASCII values in every adjacent lane pair, which is where a carry escaping a lane would show, two million random ASCII words, and whole-scan runs for every length up to 40 with the odd byte at every offset. - *32-bit* is a matter of codegen only: `uint64_t` arithmetic has the same result whatever the register width. On i686 clang emits the two adds as `addl`/`adcl`, and the inter-half carry is harmless precisely because no carry leaves a byte lane. The harness was also run with a 32-bit `Py_ssize_t`. A four-byte word was considered for those targets and rejected: an i686 eight-byte word costs 1.68 times a four-byte one, but needs half as many iterations, so for a twelve-byte key the four-byte word is about a tenth cheaper on a scan that is itself under a tenth of a lookup. That is well under a percent on the 32-bit tier, against a second code path to write and test. - *Alignment* is why the load is a `memcpy` and not a cast through `uint64_t*`, which would be both alignment and strict-aliasing UB. Every target inlines it; none falls back to a libc call, including strict alignment MIPS, which uses an `lwl`/`lwr` pair. - Compiled clean for x86_64, aarch64, armv7-hf, s390x, ppc64, ppc64le, riscv64, i686 and mips. **Scan shape**: GCC does not auto-vectorise the byte loop, since the early exit prevents it, so this is not work the compiler was already doing. Five shapes were measured with callgrind on the scan alone, one pass over twenty real HTTP header names (mean length 10.6): | scan | instructions | | --- | --- | | byte at a time | 1810 | | four-byte word, byte tail | 1209 | | eight-byte word, byte tail | 1371 | | four-byte word, overlapping tail | 1085 | | eight-byte word, overlapping tail | 986 | The byte tail, not the word width, is what hurts: a twelve-byte key does one word then four expensive scalar bytes, which is why the narrower word looked better. Replacing the tail with one more word ending at the key's end removes the effect and makes the eight-byte word the best shape at every length. **Also checked**: `entry->identity` can now be the same object as `entry->key` for a `CIMultiDict`, which is already the status quo for a plain `MultiDict` with exact-`str` keys. `_md_ensure_key()`, `md_clear()`, the resize and copy paths and `_md_check_consistency()` all treat the two as independent owned slots and never compare them, `md_traverse()` not visiting `identity` is harmless because `str` is never GC-tracked, and there is a test asserting the two references are given back. </details>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What do these changes do?
Adds six CodSpeed benchmarks for
CIMultiDictkeyed by a plainstr.Every
CIMultiDictbenchmark in the suite today uses eitheristrkeys,which serve the identity straight from the cached canonical form, or
digit-only
strkeys such asstr(i), which are already lowercase. So thecase-insensitive lowering that a mixed-case key goes through on every single
operation is currently unmeasured.
The new benchmarks use a list of 200 realistic HTTP header names, in
mixed-case and lowercase spellings, plus a non-ASCII control:
insert_str_mixed_case,insert_str_lower_case,add_str_mixed_case,fetch_str_mixed_case,fetch_str_lower_caseandfetch_str_non_ascii.This is groundwork for an optimisation of
_ci_key_to_identity(); landing thebenchmarks separately gives that change a real baseline on
masterto compareagainst, rather than a report on names that did not exist on the base commit.
Are there changes in behavior for the user?
No, this only adds benchmarks.
Is it a substantial burden for the maintainers to support this?
No, they follow the shape of the surrounding benchmarks and run on both
backends through the existing
case_insensitive_multidict_classfixture.Related issue number
N/A
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 (Claude Opus 5); reviewed by @asvetlov.
Agent run details (optional, for reviewers)
Tests:
pytest -q tests/test_multidict_benchmarks.pyon CPython 3.13.12,release C extension, 209 passed.
Lint:
pre-commit run --files CHANGES/1521.contrib.rst tests/test_multidict_benchmarks.py, all passed.make doc-spelling, buildsucceeded.
Local baseline on the paths these benchmarks cover (CPython 3.13.12,
-O3build, 1600 lookups per figure, best of 40 runs), showing why they were worth
adding:
MultiDict, plainstrCIMultiDict,istrCIMultiDict, lowercasestrCIMultiDict, mixed-casestrCIMultiDict, non-ASCIIstr