Yield from delegation in PHP - Time & Space Complexity
We want to understand how the time needed to run a generator with yield from changes as the input grows.
How does delegating to another generator affect the total steps the program takes?
Analyze the time complexity of the following code snippet.
function gen1(array $items) {
foreach ($items as $item) {
yield $item;
}
}
function gen2(array $items) {
yield from gen1($items);
}
foreach (gen2([1, 2, 3, 4, 5]) as $value) {
// process $value
}
This code uses yield from to delegate yielding values from one generator to another.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the array inside
gen1. - How many times: Once for each element in the input array.
Each item in the input array causes one yield operation, so the total steps grow directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 yields |
| 100 | About 100 yields |
| 1000 | About 1000 yields |
Pattern observation: The number of steps grows in a straight line as input size increases.
Time Complexity: O(n)
This means the time to run grows directly in proportion to the number of items we yield.
[X] Wrong: "Using yield from adds extra hidden loops making it slower than a simple loop."
[OK] Correct: yield from just passes through the values from the delegated generator without extra looping, so it doesn't add extra time beyond the original loop.
Understanding how delegation with yield from affects time helps you explain generator behavior clearly and shows you grasp efficient iteration patterns.
What if we replaced yield from with a nested loop that yields each item? How would the time complexity change?