Skip to content

Commit

Permalink
Reduce overhead of Enumerable.Chunk (#54782)
Browse files Browse the repository at this point in the history
Avoid passing the array by ref and yielding inside the loop, which defeat various optimizations (e.g. bounds checking elimination).
  • Loading branch information
stephentoub committed Jun 28, 2021
1 parent 78be359 commit 6fdb82a
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/libraries/System.Linq/src/System/Linq/Chunk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,23 @@ private static IEnumerable<TSource[]> ChunkIterator<TSource>(IEnumerable<TSource
TSource[] chunk = new TSource[size];
chunk[0] = e.Current;

for (int i = 1; i < size; i++)
int i = 1;
for (; i < chunk.Length && e.MoveNext(); i++)
{
if (!e.MoveNext())
{
Array.Resize(ref chunk, i);
yield return chunk;
yield break;
}

chunk[i] = e.Current;
}

yield return chunk;
if (i == chunk.Length)
{
yield return chunk;
}
else
{
Array.Resize(ref chunk, i);
yield return chunk;
yield break;
}
}
}
}
}
}

0 comments on commit 6fdb82a

Please sign in to comment.