Skip to content

In BTreeMap::eq, do not compare the elements if the sizes are different.#149125

Merged
bors merged 2 commits intorust-lang:mainfrom
zachs18:btreemap-eq-perf
Dec 2, 2025
Merged

In BTreeMap::eq, do not compare the elements if the sizes are different.#149125
bors merged 2 commits intorust-lang:mainfrom
zachs18:btreemap-eq-perf

Conversation

@zachs18
Copy link
Contributor

@zachs18 zachs18 commented Nov 20, 2025

Reverts #147101 in library/alloc/src/btree/

#147101 replaced some instances of code like a.len() == b.len() && a.iter().eq(&b) with just a.iter().eq(&b), but the optimization that PR introduced only applies for TrustedLen iterators, and BTreeMap's itertors are not TrustedLen, so this theoretically regressed perf for comparing large BTreeMap/BTreeSets with unequal lengths but equal prefixes, (and also made it so that comparing two different-length BTreeMap/BTreeSets with elements whose PartialEq impls that can panic now can panic, though this is not a "promised" behaviour either way (cc #149122))

Given that TrustedLen is an unsafe trait, I opted to not implement it for BTreeMap's iterators, and instead just revert the change. If someone else wants to audit BTreeMap's iterators to make sure they always return the right number of items (even in the face of incorrect user Ord impls) and then implement TrustedLen for them so that the optimization works for them, then this can be closed in favor of that (or if the perf regression is deemed too theoretical, this can be closed outright).

Example of theoretical perf regression: https://play.rust-lang.org/?version=beta&mode=release&edition=2024&gist=a37e3d61e6bf02669b251315c9a44fe2 (very rough estimates, using Instant::elapsed).
In release mode on stable the comparison takes ~23.68µs.
In release mode on beta/nightly the comparison takes ~48.351057ms.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

beta-accepted Accepted for backporting to the compiler in the beta channel. I-libs-nominated Nominated for discussion during a libs team meeting. merged-by-bors This PR was explicitly merged by bors. S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1.92 regression: Behavior change in PartialEq impl of BTreeSet?