0
0
PHPprogramming~5 mins

Yield keyword behavior in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Yield keyword behavior
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop runs from 1 to n, yielding one value each time.
  • How many times: Exactly n times, once per number.
How Execution Grows With Input

Each number from 1 to n is processed one at a time, so the steps grow directly with n.

Input Size (n)Approx. Operations
1010 steps (yield 10 times)
100100 steps (yield 100 times)
10001000 steps (yield 1000 times)

Pattern observation: The number of steps grows in a straight line as n increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to the size of the input n.

Common Mistake

[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.

Interview Connect

Understanding how yield affects time helps you explain efficient data processing in real projects.

Self-Check

What if we changed the loop to yield only every other number? How would the time complexity change?