Repository navigation
Speed up key lookups and replacements in tables - #704
Open
DicksonWu654 wants to merge 1 commit into
Open
DicksonWu654 wants to merge 1 commit into
DicksonWu654 wants to merge 1 commit into
Conversation
Replacing an existing key scanned every key in the container to recover the stored Key object, so updating many keys of a large table was quadratic. Take the stored key from the body slot that _map already points to instead. Looking up a plain str key built and validated a temporary SingleKey just to probe _map. SingleKey hashes and compares like its string, so probe _map with the string directly. Containers that have ever held a custom Key implementation keep the previous normalization and comparison scan, since such keys may not accept a str operand. Missing key errors still report the normalized key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
🛡️ Human Attestation required. A human needs to confirm this PR once before it can merge. Attest this PR — sign in with GitHub, pass the challenge, and confirm one of the statements. |
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.
Summary
Two costs in
Containergrow with the size of the table rather than with the key being accessed:Container.__setitem__on an existing key rannext(filter(lambda k: k == key, self._map))to recover the storedKeyobject, comparing the query against every key in the table. Updating every key of a table therefore takes quadratic time._mapalready points to the key's body slot, and that slot holds the stored key, so take it from there.item()and__contains__turned everystrquery into aSingleKey(which runs key-type detection and builds the quoted form) just to probe_map.SingleKeyhashes and compares like its string, so a plainstrcan probe_mapdirectly. On a miss,NonExistentKeyis still built from aSingleKey, so error messages are unchanged.A container stores only
SingleKeys unless user code passes in anotherKeyimplementation; dotted keys are split intoSingleKeys before they are stored. A boolean flag records whether any otherKeytype was ever stored. If so, the container keeps the old normalization and comparison scan, because such a key's__eq__might not accept astr. The flag is carried throughcopy,deepcopyand unpickling. Its only purpose is to keep user-definedKeysubclasses behaving exactly as before. It could be dropped if you don't think that case needs preserving.There is no other new state, and no change to the public API or pickle format.
Benchmarks
Master is
55d0768. Each pair is two fresh processes pinned to one core withtaskset, with the master-first / branch-first order alternating. Each process warms up first (plus 2 s on PyPy) and reports its fastest call. The table shows the median of those times and the median of the per-pair ratios, with their range. The machine is a shared, busy 11-vCPU Linux box (WSL2), so the ranges are wide.name/versionof every package, uv.lockname/versionof every package, poetry.lockname/versionof every package, uv.lockThe two 3.12 rows for 2,000 edits, and the poetry.lock lookup row, average each process over at least 0.4 s instead of taking its fastest call.
[tool.poetry.dependencies]table with 2,000 entries, with a new version string assigned to every key in random order.uv.lock/poetry.lockfiles.Parse times, and edits to lock files whose tables have only a few keys, show no measurable change (the bottom rows).
Behaviour checks
ruff check,ruff format --checkandpyupgrade --py39-plusare clean.mypyreports the same errors as on master.tests/test_container_updates.pycover:str,strsubclasses andKeyqueries,Keysubclasses throughcopy,deepcopyandpickle.unwrap()results, edit-then-dump output, and exact exception messages. It covered every TOML file intests/toml-testandtests/examplesplus real lock files. Earlier, roughly 17,000 generated documents and edit sequences on CPython 3.12 and 3.14 were also compared. No differences were found.Duplicate Check
_get_last_index_before_table/_insert_at). This PR only changes lookups and replacement of existing keys, so the two do not overlap.Agent Drafting Metadata
master. That re-check reran the full test suite on four interpreters, ran a separate differential check, and repeated the paired benchmarks above.🤖 Generated with Claude Code