0
0
PHPprogramming~3 mins

Why Generator function execution model in PHP? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to handle huge data smoothly without waiting or crashing your program!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
$numbers = [];
for ($i = 0; $i < 1000000; $i++) {
    $numbers[] = $i;
}
foreach ($numbers as $num) {
    echo $num . "\n";
}
After
function generateNumbers() {
    for ($i = 0; $i < 1000000; $i++) {
        yield $i;
    }
}
foreach (generateNumbers() as $num) {
    echo $num . "\n";
}
What It Enables

It enables efficient processing of large or infinite data streams without waiting or using too much memory.

Real Life Example

Reading a huge log file line by line to find errors without loading the entire file into memory.

Key Takeaways

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.