From 975b2e396b73ca9e8c6309138335019ffa35bda5 Mon Sep 17 00:00:00 2001 From: prozolic <42107886+prozolic@users.noreply.github.com> Date: Wed, 1 Apr 2026 23:50:31 +0900 Subject: [PATCH] Improve SortedSet.TreeSubSet.Clear Specify `Count` as the initial capacity of `List` 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. --- .../System/Collections/Generic/SortedSet.TreeSubSet.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.TreeSubSet.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.TreeSubSet.cs index f6c47050858cd8..e3ae983bdd7791 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.TreeSubSet.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.TreeSubSet.cs @@ -96,12 +96,12 @@ public override void Clear() return; } - List toRemove = new List(); + List toRemove = new List(Count); BreadthFirstTreeWalk(n => { toRemove.Add(n.Item); return true; }); - while (toRemove.Count != 0) + + for (int i = toRemove.Count - 1; i >= 0; i--) { - _underlying.Remove(toRemove[^1]); - toRemove.RemoveAt(toRemove.Count - 1); + _underlying.Remove(toRemove[i]); } root = null;