Match expression (PHP 8) - Time & Space 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.
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.
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.
As the number of cases grows, the number of comparisons grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 comparisons |
| 100 | Up to 100 comparisons |
| 1000 | Up to 1000 comparisons |
Pattern observation: The work grows roughly in direct proportion to the number of cases.
Time Complexity: O(n)
This means the time to find a match grows linearly with the number of cases.
[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.
Understanding how match expressions work helps you explain code efficiency clearly and shows you think about how code runs as it grows.
"What if the match expression used a hash map internally to find cases? How would the time complexity change?"