PHP & Zend Engine (50 Qs)•Part 2: Zend Engine Internals, OPcache & Memory Architecture (11 - 24)
How do Generators and the yield keyword enable memory-efficient streaming of large datasets?
senior LevelMost AskedCode ExampleSystem Design
In Simple Words: Standard functions return a complete collection, loading millions of records into memory at once. A Generator yields values one at a time on demand, consuming a flat constant amount of memory ($O(1)$ RAM).
php
function streamCsvRows(string $filePath): Generator {
$handle = fopen($filePath, 'r');
while (($row = fgetcsv($handle)) !== false) {
yield $row; // Yields one row; does not load 10GB file into RAM!
}
fclose($handle);
}