0
0
PHPprogramming~5 mins

Yield from delegation in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Yield from delegation
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

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
10About 10 yields
100About 100 yields
1000About 1000 yields

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to the number of items we yield.

Common Mistake

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

Interview Connect

Understanding how delegation with yield from affects time helps you explain generator behavior clearly and shows you grasp efficient iteration patterns.

Self-Check

What if we replaced yield from with a nested loop that yields each item? How would the time complexity change?