0
0
PHPprogramming~5 mins

Arrow functions (short closures) in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Arrow functions (short closures)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the list gets bigger, the number of times we square a number grows the same way.

Input Size (n)Approx. Operations
1010 squaring operations
100100 squaring operations
10001000 squaring operations

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input size grows.

Common Mistake

[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.

Interview Connect

Understanding how arrow functions affect performance helps you write clear code without surprises in speed.

Self-Check

"What if we replaced array_map with a foreach loop using an arrow function? How would the time complexity change?"