Advertisement
Advanced PHP, Generators & Iterators

How do generators help implement memory efficient data processing pipelines, chaining multiple transformation steps together without ever loading an entire dataset into memory at once?

Short answer

By chaining together multiple generator functions, where each generator both consumes values from a previous generator and yields transformed values to the next stage, you can build a complete data processing pipeline, such as filtering and then transforming a massive dataset…

Save PHP mock interview
Advertisement
AModel answer
By chaining together multiple generator functions, where each generator both consumes values from a previous generator and yields transformed values to the next stage, you can build a complete data processing pipeline, such as filtering and then transforming a massive dataset, where at any given moment only a single item is actually being processed and held in memory across the entire pipeline, dramatically reducing memory usage compared to processing the same pipeline using regular arrays and functions that must fully materialize each intermediate result.
function filterEven($numbers) {
    foreach ($numbers as $n) {
        if ($n % 2 === 0) yield $n;
    }
}
function double($numbers) {
    foreach ($numbers as $n) {
        yield $n * 2;
    }
}
foreach (double(filterEven(range(1, 1000000))) as $result) {
}
Real-world example
A data engineering script processes a massive CSV file through a pipeline of chained generators handling parsing, filtering, and transformation, keeping memory usage constant regardless of whether the file contains a thousand or ten million rows.
Likely follow-ups
  • How does this generator based pipeline approach compare to using array_filter and array_map on the entire dataset at once?
  • What are the limitations of this approach if you need random access to previously processed items?
Related topics