Optimize ImmutableSortedSet<T>.SetEquals to avoid unnecessary allocations#126549
Open
aw0lid wants to merge 1 commit intodotnet:mainfrom
Open
Optimize ImmutableSortedSet<T>.SetEquals to avoid unnecessary allocations#126549aw0lid wants to merge 1 commit intodotnet:mainfrom
aw0lid wants to merge 1 commit intodotnet:mainfrom
Conversation
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-collections |
f9f1622 to
1c158bc
Compare
Author
|
cc/ @stephentoub |
1c158bc to
827bfda
Compare
rosebyte
reviewed
Apr 8, 2026
...raries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs
Outdated
Show resolved
Hide resolved
827bfda to
1ae37a5
Compare
Author
|
I noticed that methods like |
666ab6c to
41c75bf
Compare
41c75bf to
390c55b
Compare
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
ImmutableSortedSet<T>.SetEqualsalways creates a new intermediateSortedSet<T>for theothercollection, leading to avoidable allocations and GC pressure, especially for large datasetsOptimization Logic
otheris anImmutableSortedSet<T>orSortedSet<T>, triggering optimized logic only if theirComparermatches.ReferenceEqualscheck and leveragesICollection<T>andIReadOnlyCollection<T>to returnfalseearly ifother.Countis less thanthis.Count..Contains()check with a dual-enumeratorwhileloop. This leverages the sorted nature of both sets to achievenew SortedSet<T>is required for generalIEnumerabletypes, the final comparison now uses the same efficientClick to expand Benchmark Source Code
Click to expand Benchmark Results
Benchmark Results (Before Optimization)
Benchmark Results (After Optimization)
Performance Analysis Summary (100,000 Elements)
🚀 Optimized Direct Paths
🛠️ Specialized Type Matching
⚖️ Fallback & General Scenarios