Skip to content

Large collection copy (ARCH7086)

Key php.performance.large-collection-copy · Severity info · Category performance

Dumping an entire generator into an array with iterator_to_array() loads all the data into memory. If you only stream over it, iterate the generator directly.

<?php
function sumLines(\Generator $lines): int
{
$all = iterator_to_array($lines);
return array_sum($all);
}
<?php
function sumLines(\Generator $lines): int
{
$total = 0;
foreach ($lines as $line) {
$total += $line;
}
return $total;
}

Stream over the generator instead of materializing data you only iterate once into an array.