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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With