Discover how to handle huge data smoothly without waiting or crashing your program!
Why Generator function execution model in PHP? - Purpose & Use Cases
Imagine you need to process a huge list of data, like reading millions of lines from a file or generating a long sequence of numbers. Doing this all at once means using a lot of memory and waiting a long time before you get any results.
Manually loading or creating all data at once is slow and can crash your program because it uses too much memory. Also, you can't start working with the first pieces of data until everything is ready, which wastes time.
Generator functions let you create data step-by-step, giving you one piece at a time. This way, your program uses less memory and can start working immediately, making it faster and more efficient.
$numbers = []; for ($i = 0; $i < 1000000; $i++) { $numbers[] = $i; } foreach ($numbers as $num) { echo $num . "\n"; }
function generateNumbers() {
for ($i = 0; $i < 1000000; $i++) {
yield $i;
}
}
foreach (generateNumbers() as $num) {
echo $num . "\n";
}It enables efficient processing of large or infinite data streams without waiting or using too much memory.
Reading a huge log file line by line to find errors without loading the entire file into memory.
Manual data handling can be slow and memory-heavy.
Generators produce data one piece at a time, saving memory.
This model lets programs start working immediately and handle big data smoothly.