Arrow functions (short closures) in PHP - Time & Space Complexity
Let's see how using arrow functions affects the time it takes for PHP code to run.
We want to know how the number of operations changes as input grows when using arrow functions.
Analyze the time complexity of the following code snippet.
$numbers = range(1, $n);
$squares = array_map(fn($x) => $x * $x, $numbers);
This code creates a list of numbers from 1 to n, then uses an arrow function to square each number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying the arrow function to each element in the array.
- How many times: Exactly once for each of the n numbers.
As the list gets bigger, the number of times we square a number grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 squaring operations |
| 100 | 100 squaring operations |
| 1000 | 1000 squaring operations |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size grows.
[X] Wrong: "Arrow functions make the code run faster, so time complexity is less than O(n)."
[OK] Correct: Arrow functions just make code shorter and cleaner, but the number of operations still depends on input size.
Understanding how arrow functions affect performance helps you write clear code without surprises in speed.
"What if we replaced array_map with a foreach loop using an arrow function? How would the time complexity change?"