From fbadbf137e24dd0e3ecfd93943b78e58ed4faff0 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Sat, 13 Feb 2021 21:38:29 -0500 Subject: [PATCH] Optimize Enumerable.Min/Max with Comparer.Default intrinsic --- src/libraries/System.Linq/src/System/Linq/Max.cs | 13 +++++-------- src/libraries/System.Linq/src/System/Linq/Min.cs | 13 +++++-------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/src/libraries/System.Linq/src/System/Linq/Max.cs b/src/libraries/System.Linq/src/System/Linq/Max.cs index 9dc4c92cd1f865..0e9c4c0476ae0c 100644 --- a/src/libraries/System.Linq/src/System/Linq/Max.cs +++ b/src/libraries/System.Linq/src/System/Linq/Max.cs @@ -448,11 +448,10 @@ public static decimal Max(this IEnumerable source) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } - Comparer comparer = Comparer.Default; TSource? value = default; - if (value == null) + using (IEnumerator e = source.GetEnumerator()) { - using (IEnumerator e = source.GetEnumerator()) + if (value == null) { do { @@ -465,6 +464,7 @@ public static decimal Max(this IEnumerable source) } while (value == null); + Comparer comparer = Comparer.Default; while (e.MoveNext()) { TSource x = e.Current; @@ -474,10 +474,7 @@ public static decimal Max(this IEnumerable source) } } } - } - else - { - using (IEnumerator e = source.GetEnumerator()) + else { if (!e.MoveNext()) { @@ -488,7 +485,7 @@ public static decimal Max(this IEnumerable source) while (e.MoveNext()) { TSource x = e.Current; - if (comparer.Compare(x, value) > 0) + if (Comparer.Default.Compare(x, value) > 0) { value = x; } diff --git a/src/libraries/System.Linq/src/System/Linq/Min.cs b/src/libraries/System.Linq/src/System/Linq/Min.cs index 9958c8468bec44..f8c7f3bec469be 100644 --- a/src/libraries/System.Linq/src/System/Linq/Min.cs +++ b/src/libraries/System.Linq/src/System/Linq/Min.cs @@ -406,11 +406,10 @@ public static decimal Min(this IEnumerable source) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } - Comparer comparer = Comparer.Default; TSource? value = default; - if (value == null) + using (IEnumerator e = source.GetEnumerator()) { - using (IEnumerator e = source.GetEnumerator()) + if (value == null) { do { @@ -423,6 +422,7 @@ public static decimal Min(this IEnumerable source) } while (value == null); + Comparer comparer = Comparer.Default; while (e.MoveNext()) { TSource x = e.Current; @@ -432,10 +432,7 @@ public static decimal Min(this IEnumerable source) } } } - } - else - { - using (IEnumerator e = source.GetEnumerator()) + else { if (!e.MoveNext()) { @@ -446,7 +443,7 @@ public static decimal Min(this IEnumerable source) while (e.MoveNext()) { TSource x = e.Current; - if (comparer.Compare(x, value) < 0) + if (Comparer.Default.Compare(x, value) < 0) { value = x; }