Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce overhead of Enumerable.Chunk #54782

Merged
merged 1 commit into from
Jun 28, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Reduce overhead of Enumerable.Chunk
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 26, 2021
commit 542d47b2708d9371a3ff86067dad596c1fe8c73c
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;
}
}
}
}
}
}