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

Commit 6cf2b4c

Browse files
committed
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.
1 parent 6026ec5 commit 6cf2b4c

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

src/System.Linq/src/System/Linq/Enumerable.cs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3442,18 +3442,21 @@ internal Buffer(IEnumerable<TElement> source, bool queryInterfaces = true)
34423442

34433443
if (items == null)
34443444
{
3445-
foreach (TElement item in source)
3445+
using (IEnumerator<TElement> e = source.GetEnumerator())
34463446
{
3447-
if (items == null)
3447+
if (e.MoveNext())
34483448
{
34493449
items = new TElement[4];
3450+
items[0] = e.Current;
3451+
count = 1;
3452+
3453+
while (e.MoveNext())
3454+
{
3455+
if (items.Length == count) Array.Resize(ref items, checked(count * 2));
3456+
items[count] = e.Current;
3457+
++count;
3458+
}
34503459
}
3451-
else if (items.Length == count)
3452-
{
3453-
Array.Resize(ref items, checked(count * 2));
3454-
}
3455-
items[count] = item;
3456-
count++;
34573460
}
34583461
}
34593462

0 commit comments

Comments
 (0)