From ea4d1c73364fa09e8d5c621b03b95d51166d212e Mon Sep 17 00:00:00 2001 From: Matthew Parkinson Date: Thu, 22 Sep 2016 13:20:11 +0100 Subject: [PATCH 1/2] Fixed performance of Min/Max in SortedSet. The existing implementation of Min/Max calls InOrderWalkTree, which perform an allocation of a stack for traversing the tree. But when you are finding the smallest or largest element in a tree there is no need to perform this allocation. This is an optimised version that directly finds the smallest or largest element. --- .../System/Collections/Generic/SortedSet.cs | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/System.Collections/src/System/Collections/Generic/SortedSet.cs b/src/System.Collections/src/System/Collections/Generic/SortedSet.cs index b1febacf1cc3..dba35b573248 100644 --- a/src/System.Collections/src/System/Collections/Generic/SortedSet.cs +++ b/src/System.Collections/src/System/Collections/Generic/SortedSet.cs @@ -1845,9 +1845,18 @@ public T Min { get { - T ret = default(T); - InOrderTreeWalk(delegate (SortedSet.Node n) { ret = n.Item; return false; }); - return ret; + if (_root == null) + { + return default(T); + } + + var current = _root; + while (current.Left != null) + { + current = current.Left; + } + + return current.Item; } } @@ -1855,9 +1864,18 @@ public T Max { get { - T ret = default(T); - InOrderTreeWalk(delegate (SortedSet.Node n) { ret = n.Item; return false; }, true); - return ret; + if (_root == null) + { + return default(T); + } + + var current = _root; + while (current.Right != null) + { + current = current.Right; + } + + return current.Item; } } From af7cc0de2e95a515d032020d48c24de5a5854e63 Mon Sep 17 00:00:00 2001 From: Matthew Parkinson Date: Thu, 22 Sep 2016 16:02:20 +0100 Subject: [PATCH 2/2] Code review feedback --- .../src/System/Collections/Generic/SortedSet.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Collections/src/System/Collections/Generic/SortedSet.cs b/src/System.Collections/src/System/Collections/Generic/SortedSet.cs index dba35b573248..df67684635c4 100644 --- a/src/System.Collections/src/System/Collections/Generic/SortedSet.cs +++ b/src/System.Collections/src/System/Collections/Generic/SortedSet.cs @@ -1850,7 +1850,7 @@ public T Min return default(T); } - var current = _root; + Node current = _root; while (current.Left != null) { current = current.Left; @@ -1869,7 +1869,7 @@ public T Max return default(T); } - var current = _root; + Node current = _root; while (current.Right != null) { current = current.Right;