0
0
PHPprogramming~5 mins

Match expression (PHP 8) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Match expression (PHP 8)
O(n)
Understanding Time Complexity

Let's see how the time it takes to run a match expression changes as we add more cases.

We want to know how the number of cases affects the work done.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$value = 3;
switch ($value) {
    case 1:
    case 2:
        $result = 'One or Two';
        break;
    case 3:
        $result = 'Three';
        break;
    default:
        $result = 'Other';
}

// Using match expression
$result = match ($value) {
    1, 2 => 'One or Two',
    3 => 'Three',
    default => 'Other',
};
    

This code uses a match expression to select a result based on the value.

Identify Repeating Operations

Look for repeated checks or comparisons.

  • Primary operation: Comparing the input value to each case value.
  • How many times: Up to the number of cases, until a match is found.
How Execution Grows With Input

As the number of cases grows, the number of comparisons grows too.

Input Size (n)Approx. Operations
10Up to 10 comparisons
100Up to 100 comparisons
1000Up to 1000 comparisons

Pattern observation: The work grows roughly in direct proportion to the number of cases.

Final Time Complexity

Time Complexity: O(n)

This means the time to find a match grows linearly with the number of cases.

Common Mistake

[X] Wrong: "Match expressions check all cases at once, so time stays the same no matter how many cases there are."

[OK] Correct: The match expression checks cases one by one until it finds a match, so more cases mean more checks.

Interview Connect

Understanding how match expressions work helps you explain code efficiency clearly and shows you think about how code runs as it grows.

Self-Check

"What if the match expression used a hash map internally to find cases? How would the time complexity change?"