Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit cd15d09

Browse files
committed
Improve SortedSet.BreadthFirstTreeWalk
SortedSet's BreadthFirstTreeWalk (which is used by several members, such as RemoveWhere) is currently using a List as a queue, doing a RemoveAt(0) to dequeue, which will incur the cost of shifting all elements down. Using a Queue is both cleaner and better performing.
1 parent 44f26bf commit cd15d09

File tree

1 file changed

+10
-12
lines changed
  • src/System.Collections/src/System/Collections/Generic

1 file changed

+10
-12
lines changed

src/System.Collections/src/System/Collections/Generic/SortedSet.cs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -257,25 +257,24 @@ internal virtual bool BreadthFirstTreeWalk(TreeWalkPredicate<T> action)
257257
return true;
258258
}
259259

260-
List<Node> processQueue = new List<Node>();
261-
processQueue.Add(_root);
260+
Queue<Node> processQueue = new Queue<Node>();
261+
processQueue.Enqueue(_root);
262262
Node current;
263263

264264
while (processQueue.Count != 0)
265265
{
266-
current = processQueue[0];
267-
processQueue.RemoveAt(0);
266+
current = processQueue.Dequeue();
268267
if (!action(current))
269268
{
270269
return false;
271270
}
272271
if (current.Left != null)
273272
{
274-
processQueue.Add(current.Left);
273+
processQueue.Enqueue(current.Left);
275274
}
276275
if (current.Right != null)
277276
{
278-
processQueue.Add(current.Right);
277+
processQueue.Enqueue(current.Right);
279278
}
280279
}
281280
return true;
@@ -2084,25 +2083,24 @@ internal override bool BreadthFirstTreeWalk(TreeWalkPredicate<T> action)
20842083
return true;
20852084
}
20862085

2087-
List<Node> processQueue = new List<Node>();
2088-
processQueue.Add(_root);
2086+
Queue<Node> processQueue = new Queue<Node>();
2087+
processQueue.Enqueue(_root);
20892088
Node current;
20902089

20912090
while (processQueue.Count != 0)
20922091
{
2093-
current = processQueue[0];
2094-
processQueue.RemoveAt(0);
2092+
current = processQueue.Dequeue();
20952093
if (IsWithinRange(current.Item) && !action(current))
20962094
{
20972095
return false;
20982096
}
20992097
if (current.Left != null && (!_lBoundActive || Comparer.Compare(_min, current.Item) < 0))
21002098
{
2101-
processQueue.Add(current.Left);
2099+
processQueue.Enqueue(current.Left);
21022100
}
21032101
if (current.Right != null && (!_uBoundActive || Comparer.Compare(_max, current.Item) > 0))
21042102
{
2105-
processQueue.Add(current.Right);
2103+
processQueue.Enqueue(current.Right);
21062104
}
21072105
}
21082106
return true;

0 commit comments

Comments
 (0)