Memory efficiency with generators in PHP - Time & Space Complexity
We want to see how using generators affects the time it takes to run code that processes many items.
How does the program's work grow when we use generators instead of regular arrays?
Analyze the time complexity of the following code snippet.
function numbersGenerator($n) {
for ($i = 0; $i < $n; $i++) {
yield $i;
}
}
foreach (numbersGenerator(1000) as $num) {
// process $num
}
This code generates numbers from 0 to n-1 one by one without storing them all at once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop runs from 0 to n-1 yielding one number each time.
- How many times: Exactly n times, once per number generated.
Each number is generated and processed one at a time, so work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The work grows in a straight line as n increases.
Time Complexity: O(n)
This means the time to run the code grows directly in proportion to the number of items generated.
[X] Wrong: "Using generators makes the code run faster because it uses less memory."
[OK] Correct: Generators save memory but do not reduce the number of steps the program takes to process each item.
Understanding how generators affect time helps you explain efficient data processing in real projects.
"What if we replaced the generator with an array that holds all numbers at once? How would the time complexity change?"
Practice
Solution
Step 1: Understand how generators produce values
Generators useyieldto produce one value at a time instead of creating the whole list in memory.Step 2: Compare memory usage with arrays
Returning an array stores all values at once, using more memory. Generators save memory by generating values on demand.Final Answer:
It uses less memory by producing values one at a time. -> Option BQuick Check:
Generators save memory = C [OK]
- Thinking generators cache all values like arrays
- Confusing speed with memory usage
- Believing generators return all values at once
Solution
Step 1: Identify generator syntax
Generators use theyieldkeyword inside functions to produce values one at a time.Step 2: Check each option
function gen() { yield 1; yield 2; yield 3; } usesyieldcorrectly. Others either return arrays or print values, not generators.Final Answer:
function gen() { yield 1; yield 2; yield 3; } -> Option AQuick Check:
Generators use yield = B [OK]
- Using return instead of yield for generators
- Confusing echo/print with yield
- Missing yield keyword in generator functions
function gen() {
for ($i = 1; $i <= 3; $i++) {
yield $i * 2;
}
}
foreach (gen() as $value) {
echo $value . ' ';
}Solution
Step 1: Analyze the generator loop
The loop runs from 1 to 3, yielding $i * 2 each time: 2, 4, 6.Step 2: Understand foreach output
Each yielded value is printed with a space, so output is "2 4 6 ".Final Answer:
2 4 6 -> Option AQuick Check:
Yielded values doubled = A [OK]
- Assuming yield can't be used in loops
- Printing loop index instead of multiplied value
- Confusing yield with return inside loops
function gen() {
yield 1;
return 2;
yield 3;
}Solution
Step 1: Understand return behavior in generators
When a return statement is reached, the generator stops and no further yields run.Step 2: Analyze the code flow
After yielding 1, the function returns 2, soyield 3is never executed.Final Answer:
The yield after return will never execute. -> Option CQuick Check:
Return stops generator = A [OK]
- Thinking return after yield is invalid syntax
- Expecting all yields to run after return
- Confusing echo with yield in generators
Solution
Step 1: Understand memory usage for large files
Loading the entire file into memory (Read the entire file into an array, then yield each line.) uses a lot of memory, which is inefficient.Step 2: Use generator to yield lines one by one
Opening the file and yielding each line as it is read (Use a generator function that opens the file and yields one line at a time.) saves memory by processing lines lazily.Step 3: Evaluate other options
Use a generator that yields the whole file content as a single string. yields the whole file at once, no memory saving. Read and yield lines only after closing the file. yields after closing file, which is invalid.Final Answer:
Use a generator function that opens the file and yields one line at a time. -> Option DQuick Check:
Yield lines lazily for memory efficiency = D [OK]
- Loading entire file before yielding
- Yielding whole file content as one string
- Trying to yield after file is closed
Ready to prove it?
Pass the test and this pattern moves unknown
