IteratorAggregate interface in PHP - Time & Space Complexity
When using the IteratorAggregate interface in PHP, we want to understand how the time to get items grows as the collection size grows.
We ask: How does looping through the items behave as the list gets bigger?
Analyze the time complexity of this PHP code using IteratorAggregate.
class MyCollection implements IteratorAggregate {
private array $items;
public function __construct(array $items) {
$this->items = $items;
}
public function getIterator(): Traversable {
return new ArrayIterator($this->items);
}
}
$n = 10; // example value for $n
$collection = new MyCollection(range(1, $n));
foreach ($collection as $item) {
// process $item
}
This code creates a collection that can be looped over using IteratorAggregate, returning an iterator over an array of items.
Look at what repeats when looping through the collection.
- Primary operation: Looping through each item in the array inside the iterator.
- How many times: Once for each item in the collection, so n times if there are n items.
As the number of items grows, the loop runs once per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loops |
| 100 | 100 loops |
| 1000 | 1000 loops |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to loop through the collection grows in a straight line with the number of items.
[X] Wrong: "Using IteratorAggregate makes looping slower because it adds extra steps."
[OK] Correct: The interface just provides a way to get the iterator; the main work is still looping through each item once, so the time grows linearly.
Understanding how interfaces like IteratorAggregate affect performance helps you explain your code choices clearly and shows you know how data size impacts speed.
"What if the getIterator method returned a generator instead of an ArrayIterator? How would the time complexity change?"