Intermediate LevelPHP 8+
How do PHP Generators (yield keyword) process massive datasets without exhausting memory_limit?
❓ Interview Prompt: Explain PHP Generators, stateful iterator execution with yield, memory optimization for large files, and Generator objects.
Standard functions return a single value and terminate. A Generator function uses the 'yield' keyword to produce a sequence of values lazily over time.
Memory Optimization Advantage:
If you read a 2GB CSV file into a standard array, PHP attempts to allocate 2GB of RAM, throwing a Fatal "Allowed memory size exhausted" error.
With a Generator, PHP yields one item at a time into memory during iteration, keeping total RAM usage under 2MB regardless of dataset size!
Code Implementation Example
php
<?php
// Generator reading multi-gigabyte CSV file line-by-line using < 2MB RAM!
function readLargeCsv(string $filePath): Generator {
$handle = fopen($filePath, 'r');
try {
while (($row = fgetcsv($handle)) !== false) {
yield $row; // Yields single row to loop, pausing execution!
}
} finally {
fclose($handle);
}
}
// Memory remains virtually flat during 1,000,000 row loop!
foreach (readLargeCsv('massive_export.csv') as $row) {
processRow($row);
}💡Processing massive CSV datasets using PHP Generator function with yield.
🎯 Interview Key Takeaway
Generators yield items lazily one at a time during iteration, allowing processing of massive datasets under 2MB RAM.
#Generators#yield#Memory Optimization#Intermediate
Back to all PHP 8+ Questions→