Skip to content

Commit

Permalink
Clear list in Enumerable.Chunk prior to yielding (#72637)
Browse files Browse the repository at this point in the history
To avoid the iterator keeping alive references unnecessarily.  If the consumer takes their time in processing the resulting array and nulls out values as they go, we don't want the list referenced by the enumerator still keeping those objects referenced.
  • Loading branch information
stephentoub authored Jul 22, 2022
1 parent 0e7432f commit 44be09d
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/libraries/System.Linq/src/System/Linq/Chunk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,22 +55,21 @@ private static IEnumerable<TSource[]> ChunkIterator<TSource>(IEnumerable<TSource
if (e.MoveNext())
{
List<TSource> chunkBuilder = new();
while (true)
int lastLength;
do
{
do
{
chunkBuilder.Add(e.Current);
}
while (chunkBuilder.Count < size && e.MoveNext());

yield return chunkBuilder.ToArray();

if (chunkBuilder.Count < size || !e.MoveNext())
{
yield break;
}
TSource[] array = chunkBuilder.ToArray();
chunkBuilder.Clear();
lastLength = array.Length;
yield return array;
}
while (lastLength >= size && e.MoveNext());
}
}
}
Expand Down

0 comments on commit 44be09d

Please sign in to comment.