1.2.1133. Simple Switch And Match¶
Switch() and match() are faster when relying only on literal integers or strings.
Since PHP 7.2, simple switches, that use only literal strings or integers, are optimized. The bigger the switch, the greater the gain. Match() was introduced in PHP 8.0
In particular, this optimisation doesn’t work with any expressions (constant or not), function call, methodcall, constant usage, etc. Only literal values, string or integer.
When the switch is partially build of literals, it is worth splitting the switch in two : first level, only with the literal cases, and, in the default, the dynamic values. This brings some performances, though it is a micro-optimisation.
<?php
// Optimized switch.
switch($b) {
case "a":
break;
case "b":
break;
case "c":
break;
case "d":
break;
default :
break;
}
// Unoptimized switch.
// Try moving the foo() call in the default, to keep the rest of the switch optimized.
switch($c) {
case "a":
break;
case foo($b):
break;
case C:
break;
case "c":
break;
case "d":
break;
default :
break;
}
// Partially optimised switch
// Try moving the foo() call in the default, to keep the rest of the switch optimized.
switch($c) {
case "a":
break;
case "c":
break;
case "d":
break;
default :
switch($c) {
case foo($b):
break;
case C:
break;
default :
break;
}
break;
}
?>
See also PHP 7.2’s “switch” optimisations.
1.2.1133.1. Connex PHP features¶
1.2.1133.1.1. Suggestions¶
Split the switch between literal and dynamic cases
Remove the dynamic cases from the switch
Move the most common case to the beginning of the switch
1.2.1133.1.2. Specs¶
Short name |
Performances/SimpleSwitch |
Rulesets |
|
Exakat since |
1.0.1 |
PHP Version |
With PHP 7.2 and more recent |
Severity |
Major |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Available in |