From ab0e299ac7c1640fad2b6f094f32036b194768bb Mon Sep 17 00:00:00 2001 From: Stuart Turner Date: Mon, 23 Jan 2023 09:54:00 -0600 Subject: [PATCH] Improve `AggregateRight` performance --- Source/SuperLinq/AggregateRight.cs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Source/SuperLinq/AggregateRight.cs b/Source/SuperLinq/AggregateRight.cs index 73364e9c..0c88ef0b 100644 --- a/Source/SuperLinq/AggregateRight.cs +++ b/Source/SuperLinq/AggregateRight.cs @@ -27,15 +27,15 @@ public static TSource AggregateRight(this IEnumerable source, Guard.IsNotNull(source); Guard.IsNotNull(func); - using var e = source.Reverse().GetEnumerator(); + var list = source is IList l ? l : source.ToList(); - if (!e.MoveNext()) + if (list.Count == 0) ThrowHelper.ThrowInvalidOperationException("Sequence contains no elements"); - var seed = e.Current; + var seed = list[^1]; - while (e.MoveNext()) - seed = func(e.Current, seed); + for (var i = list.Count - 2; i >= 0; i--) + seed = func(list[i], seed); return seed; } @@ -70,8 +70,10 @@ public static TAccumulate AggregateRight(this IEnumerable< Guard.IsNotNull(source); Guard.IsNotNull(func); - foreach (var i in source.Reverse()) - seed = func(i, seed); + var list = source is IList l ? l : source.ToList(); + + for (var i = list.Count - 1; i >= 0; i--) + seed = func(list[i], seed); return seed; }