Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default in switch case

The below is the code which I need to optimize and planned that it would be good to move to the switch construct. But I can compare in case. So I planned to make the comparison (len > 3) as the default case.

If I make the comparison part (len > 3) as the default case and add the default as the first in the switch, will it be faster?

Or how can I make the below code as a switch statement?

if ( len > 3 ) {
    // Which will happen more often;
}
else if ( len == 3 ) {
    // Next case which may occur often;

} else if ( len == 2 ) {
    // The next priority case;

} else {
    // And this case occurs rarely;

}
like image 390
2vision2 Avatar asked Dec 11 '22 19:12

2vision2


1 Answers

Probably not. Both if...else and switch...case are high-level constructs. What slows you down is the branch prediction. The better your prediction is the faster your code will run. You should put your most occurring case in first if, second in the else if and so on, just like you wrote. For switch the result depends on the internal compiler implementation which can reorder the cases despite your own order. The default should be actually reserved for the less occurring situations because rest of the conditions must be checked before falling back to default.

To conclude all this, performance-wise usage of if...else is optimal as long as you set your conditions in the correct order. Regarding switch...case it's compiler specific and depends on the applied optimizations.

Also note that switch...case is more limited than if...else since it supports only simple comparison of values.

like image 146
SomeWittyUsername Avatar answered Feb 10 '23 03:02

SomeWittyUsername