Skip to content

Use linear probing after the initial slot in the hash table - #1473

Closed
asvetlov wants to merge 1 commit into
aio-libs:masterfrom
asvetlov:experiment/linear-probe
Closed

asvetlov wants to merge 1 commit into
aio-libs:masterfrom
asvetlov:experiment/linear-probe

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

Switches the internal hash table probe sequence, in both the C
extension and the pure Python implementation, from CPython dict's
perturbation formula to linear probing after the initial slot.
Collision chains land in consecutive slots instead of being
scattered across the table, which is friendlier to the cache; the
effect is largest when many values are added under the same key.

Are there changes in behavior for the user?

No, only performance. Iteration order is unaffected since it comes
from the separate entries list, not the probe sequence.

Is it a substantial burden for the maintainers to support this?

No. The change is contained to the probe-sequence step in
htkeys_build_indices, htkeys_find_empty_slot and
htkeysiter_next (C extension) and their pure Python counterparts,
with no public API change.

Related issue number

N/A. Related to #1466, which targets the same slow path (many values
added under one key) with a different, more targeted technique: it
caches where the probe sequence's post-perturbation "tail" last ended
and resumes from there, leaving the general probe sequence untouched.
This PR is a simpler alternative offered for comparison; see the
benchmark note below.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes N/A
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt N/A, file does not exist in this repo
  • Add a new news fragment into the CHANGES/ folder
  • make doc-spelling passes and any new technical words are added to docs/spelling_wordlist.txt
Agent run details (optional, for reviewers)

No new dedicated test was added; the existing suite (including the
hypothesis-marked property tests) already exercises every changed
line under both backends, confirmed via the coverage report before
committing.

Tests: pytest -q on master before the change and on this branch,
both backends parametrized: 2020 passed, 10 skipped, both runs.
pytest -q -m hypothesis: 142 passed. Debug build with
MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1, ASan+UBSan
preloaded: 2009 passed, no sanitizer reports.

Lint: pre-commit run on the changed files (ruff, clang-format,
mypy x2): all passed. make doc-spelling: passed.

Benchmark (own microbenchmark, not the codspeed one from #1465,
wall clock, C extension, release build): building a MultiDict from
200 keys with 200 add() calls each (40000 inserts total, all
colliding within each key's 200-entry chain) went from ~20-24ms to
~6-8ms, roughly 3x. Unique-key workloads (build/get/iterate on 20000
distinct keys) were unchanged within noise. This is a constant-factor
cache-locality win; each insert is still O(chain length). By
contrast, #1466's own numbers show an asymptotic improvement for the
same scenario (2.2B to 6.8M instructions for 20000 values under one
key), since it stops re-walking already-placed entries entirely. The
two approaches are not mutually exclusive but this PR does not
attempt to combine them.

Drafted with Claude Code; reviewed by @asvetlov.

Replaces CPython dict's perturbation-based probe sequence with
linear probing for every step after the initial slot, in both the
C extension and the pure Python implementation. This keeps
collision chains in consecutive slots instead of scattering them
across the table, which is friendlier to the cache; the effect is
largest when many values are added under the same key.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 16, 2026
@codspeed

codspeed Bot commented Sep 16, 2026

Copy link
Copy Markdown

Merging this PR will regress 3 benchmarks

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 18 improved benchmarks
❌ 3 regressed benchmarks
✅ 245 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_multidict_getall_str_miss[cs-py] 7.3 ms 8.9 ms -18.68%
❌ test_cimultidict_getall_istr_miss[py] 7.7 ms 9.4 ms -18.64%
❌ test_multidict_getall_str_miss[ci-py] 8.4 ms 10.1 ms -16.34%
⚡ test_multidict_add_same_key[cs-py] 1,498 ms 765 ms +95.8%
⚡ test_multidict_add_same_key[ci-py] 1,499.6 ms 766.6 ms +95.62%
⚡ test_create_multidict_with_items_same_key[cs-py] 954.3 ms 503.1 ms +89.71%
⚡ test_create_multidict_with_items_same_key[ci-py] 956 ms 504.4 ms +89.52%
⚡ test_multidict_insert_str[cs-py] 2.9 ms 2.5 ms +17.67%
⚡ test_cimultidict_insert_istr[py] 3 ms 2.6 ms +17.54%
⚡ test_multidict_insert_str[ci-py] 3.1 ms 2.7 ms +17.07%
⚡ test_multidict_setitem_str[cs-py] 3.3 ms 2.9 ms +15.71%
⚡ test_cimultidict_setitem_istr[py] 3.4 ms 3 ms +15.62%
⚡ test_multidict_setitem_str[ci-py] 3.5 ms 3 ms +14.86%
⚡ test_multidict_add_same_key[cs-c] 3.2 ms 2.8 ms +13.85%
⚡ test_multidict_delitem_str[cs-py] 2.6 ms 2.4 ms +11.54%
⚡ test_multidict_delitem_str[ci-py] 2.8 ms 2.5 ms +10.92%
⚡ test_cimultidict_delitem_istr[py] 2.7 ms 2.5 ms +10.89%
⚡ test_multidict_add_same_key[ci-c] 4.5 ms 4.1 ms +10.69%
⚡ test_multidict_update_str[cs-py] 2.4 ms 2.2 ms +10.21%
⚡ test_cimultidict_update_istr[py] 2.5 ms 2.3 ms +9.39%
... ... ... ... ...

ℹ️ Only the first 20 benchmarks are displayed. Go to the app to view all benchmarks.

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing asvetlov:experiment/linear-probe (70e46fc) with master (684b085)

Open in CodSpeed

@codecov

codecov Bot commented Sep 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (684b085) to head (70e46fc).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1473   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           37        37           
  Lines         5792      5782   -10     
  Branches       489       489           
=========================================
- Hits          5792      5782   -10     
Flag Coverage Δ
CI-GHA 100.00% <100.00%> (ø)
pytest 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@asvetlov

Copy link
Copy Markdown
Member Author

The experiment show bad result with pathological cases, when different keys land on the same slot

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

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant