Yield keyword behavior in PHP - Time & Space Complexity
Let's explore how using the yield keyword affects the time it takes for a PHP function to run.
We want to know how the number of steps changes as the input grows when using yield.
Analyze the time complexity of the following code snippet.
function countToN(int $n) {
for ($i = 1; $i <= $n; $i++) {
yield $i;
}
}
foreach (countToN(5) as $number) {
echo $number . " ";
}
This code yields numbers from 1 to n one by one, instead of returning all at once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop runs from 1 ton, yielding one value each time. - How many times: Exactly
ntimes, once per number.
Each number from 1 to n is processed one at a time, so the steps grow directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps (yield 10 times) |
| 100 | 100 steps (yield 100 times) |
| 1000 | 1000 steps (yield 1000 times) |
Pattern observation: The number of steps grows in a straight line as n increases.
Time Complexity: O(n)
This means the time to run grows directly in proportion to the size of the input n.
[X] Wrong: "Using yield makes the function run instantly regardless of input size."
[OK] Correct: yield delays output but the loop still runs n times, so the total work grows with n.
Understanding how yield affects time helps you explain efficient data processing in real projects.
What if we changed the loop to yield only every other number? How would the time complexity change?