Strategy pattern in PHP - Time & Space Complexity
When using the Strategy pattern, we want to understand how the program's running time changes as we use different strategies.
We ask: how does choosing and running a strategy affect the total work done?
Analyze the time complexity of the following code snippet.
interface Strategy {
public function execute(array $data): array;
}
class ConcreteStrategyA implements Strategy {
public function execute(array $data): array {
return array_map(fn($x) => $x * 2, $data);
}
}
class Context {
private Strategy $strategy;
public function __construct(Strategy $strategy) {
$this->strategy = $strategy;
}
public function run(array $data): array {
return $this->strategy->execute($data);
}
}
This code runs a chosen strategy on an array of data, transforming it according to the strategy's rules.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
array_mapfunction inside the strategy loops over each element of the input array. - How many times: It runs once for each item in the input array.
As the input array gets bigger, the number of times the strategy's execute method processes elements grows directly with the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls inside array_map |
| 100 | 100 function calls inside array_map |
| 1000 | 1000 function calls inside array_map |
Pattern observation: The work grows evenly as the input size grows; doubling input doubles work.
Time Complexity: O(n)
This means the time to run the strategy grows in direct proportion to the number of items in the input.
[X] Wrong: "The Strategy pattern adds extra loops and makes the program slower by a lot."
[OK] Correct: The pattern itself just chooses which code to run; it does not add extra loops beyond what the chosen strategy does.
Understanding how design patterns affect time helps you explain your choices clearly and shows you think about both design and performance.
"What if the strategy used nested loops inside execute? How would the time complexity change?"