Generator return values in PHP - Time & Space Complexity
Let's explore how the time needed to get values from a generator grows as we use it more.
We want to see how the generator's return value affects the work done.
Analyze the time complexity of the following code snippet.
function countToN(int $n): Generator {
for ($i = 1; $i <= $n; $i++) {
yield $i;
}
return 'Done';
}
$gen = countToN(5);
foreach ($gen as $value) {
echo $value . "\n";
}
$returnValue = $gen->getReturn();
This code yields numbers from 1 to n, then returns a final message after finishing.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop yielding values one by one.
- How many times: Exactly n times, once for each number from 1 to n.
Each time we ask the generator for a value, it does one step of work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps to yield values + 1 step to return |
| 100 | 100 steps to yield values + 1 step to return |
| 1000 | 1000 steps to yield values + 1 step to return |
Pattern observation: The work grows directly with n, plus a tiny extra step at the end.
Time Complexity: O(n)
This means the time to get all values and the return grows in a straight line with how many values we want.
[X] Wrong: "The return value makes the generator run again for each call."
[OK] Correct: The generator only runs once through the loop; the return value is just stored and accessed after finishing.
Understanding how generators yield and return helps you explain efficient data processing in real projects.
"What if the generator yielded values conditionally inside nested loops? How would the time complexity change?"