From 6cf2b4cd08faa6079d833d1aa207fcbdb7ddd79f Mon Sep 17 00:00:00 2001 From: Jon Hanna Date: Tue, 18 Aug 2015 18:22:22 +0100 Subject: [PATCH] Don't do null check on every loop when filling buffer. Buffer has an optimisation of using a null array to represent an empty state, that also plays well with it being a value type. When the buffer is filled from an enumerable, this possible null state is checked for on every loop. Restructure to avoid this redundancy. --- src/System.Linq/src/System/Linq/Enumerable.cs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/System.Linq/src/System/Linq/Enumerable.cs b/src/System.Linq/src/System/Linq/Enumerable.cs index 6924c11f0612..b2acae99e13b 100644 --- a/src/System.Linq/src/System/Linq/Enumerable.cs +++ b/src/System.Linq/src/System/Linq/Enumerable.cs @@ -3442,18 +3442,21 @@ internal Buffer(IEnumerable source, bool queryInterfaces = true) if (items == null) { - foreach (TElement item in source) + using (IEnumerator e = source.GetEnumerator()) { - if (items == null) + if (e.MoveNext()) { items = new TElement[4]; + items[0] = e.Current; + count = 1; + + while (e.MoveNext()) + { + if (items.Length == count) Array.Resize(ref items, checked(count * 2)); + items[count] = e.Current; + ++count; + } } - else if (items.Length == count) - { - Array.Resize(ref items, checked(count * 2)); - } - items[count] = item; - count++; } }