0
0
PHPprogramming~5 mins

Generator return values in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generator return values
O(n)
Understanding Time 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.

Scenario Under Consideration

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

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.
How Execution Grows With Input

Each time we ask the generator for a value, it does one step of work.

Input Size (n)Approx. Operations
1010 steps to yield values + 1 step to return
100100 steps to yield values + 1 step to return
10001000 steps to yield values + 1 step to return

Pattern observation: The work grows directly with n, plus a tiny extra step at the end.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Understanding how generators yield and return helps you explain efficient data processing in real projects.

Self-Check

"What if the generator yielded values conditionally inside nested loops? How would the time complexity change?"