Why closures matter in PHP - Performance Analysis
We want to see how using closures in PHP affects how long a program takes to run.
Specifically, we ask: how does the program's work grow when closures are involved?
Analyze the time complexity of the following code snippet.
$numbers = range(1, $n);
$results = [];
$filterEven = function($num) {
return $num % 2 === 0;
};
foreach ($numbers as $number) {
if ($filterEven($number)) {
$results[] = $number;
}
}
This code creates a list of numbers, defines a closure to check even numbers, and uses it to filter the list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Exactly once for each number, so n times.
- Closure call: The closure runs once per number inside the loop.
As the list gets bigger, the program checks each number once using the closure.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the number of items; doubling items doubles work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Using a closure makes the code slower by a lot because it adds extra steps."
[OK] Correct: The closure is just a small function called inside the loop, so it adds a tiny fixed cost per item, not a big change in growth.
Understanding how closures affect time helps you explain your code choices clearly and shows you think about efficiency in real projects.
"What if the closure itself contained a loop over the entire list? How would the time complexity change?"