Improve SortedSet<T>.TreeSubSet.Clear#126410
Merged
eiriktsarpalis merged 3 commits intodotnet:mainfrom Apr 20, 2026
Merged
Conversation
Specify `Count` as the initial capacity of `List<T>` to avoid unnecessary heap reallocations while collecting items via `BreadthFirstTreeWalk`. Replace the `while` loop that called `RemoveAt(Count - 1)` after each removal with a simple reverse `for` loop over the list by index.
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-collections |
Contributor
There was a problem hiding this comment.
Pull request overview
This PR optimizes SortedSet<T>.TreeSubSet.Clear() in System.Collections by reducing List<T> growth overhead during item collection and simplifying the removal loop, aiming to lower allocations and improve clear-time performance for subset views.
Changes:
- Pre-allocate the removal buffer with
Countas the initialList<T>capacity to avoid repeated internal array growth. - Replace the
whileloop that repeatedly removed the last list element with a reverse index-basedforloop.
This was referenced Apr 1, 2026
Open
This was referenced Apr 19, 2026
danmoseley
approved these changes
Apr 20, 2026
Member
danmoseley
left a comment
There was a problem hiding this comment.
seems ok. @eiriktsarpalis any concerns?
eiriktsarpalis
approved these changes
Apr 20, 2026
Member
|
Thanks! |
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
This PR specify
Countas the initial capacity ofList<T>to avoid unnecessary heap reallocations while collecting items viaBreadthFirstTreeWalk, and replace thewhileloop that calledRemoveAt(Count - 1)after each removal with a simple reverseforloop over the list by index.Benchmark Results