How can the switch/case statement be optimized for better performance?
Switch/case statements can be optimized for better performance by using a hash map instead of multiple case statements. This can reduce the time complexity from O(n) to O(1) for finding the correct case. By using an associative array where the keys are the case values and the values are the corresponding actions, we can directly access the action without having to iterate through each case.
$actionMap = [
'case1' => function() {
// Action for case1
},
'case2' => function() {
// Action for case2
},
'case3' => function() {
// Action for case3
}
];
$case = 'case2';
if (isset($actionMap[$case])) {
$actionMap[$case]();
} else {
// Default action
}