Reduce overhead of Enumerable.Chunk (#54782)
authorStephen Toub <stoub@microsoft.com>
Mon, 28 Jun 2021 14:42:53 +0000 (10:42 -0400)
committerGitHub <noreply@github.com>
Mon, 28 Jun 2021 14:42:53 +0000 (10:42 -0400)
Avoid passing the array by ref and yielding inside the loop, which defeat various optimizations (e.g. bounds checking elimination).

src/libraries/System.Linq/src/System/Linq/Chunk.cs

index 661edaa..2a2ddd4 100644 (file)
@@ -55,20 +55,23 @@ namespace System.Linq
                 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;
+                }
             }
         }
     }
-}
\ No newline at end of file
+}