I read on StackOverflow that using
if(someCondition)
{
someCode();
}
else
{
alternateCode();
}
can be inefficient due to susceptibility to branch misprediction (see this question for example).
So is a switch
-construct, e.g.,
switch (someCondition)
{
case (someCase):
something();
break;
case (otherCase):
someOtherInstructions();
break;
default:
defaultAction();
break;
}
any different in this respect (besides the fact that I have allowed for three possibilities)?
if
statements aren't "expensive", conditional branches may be. The issue isn't which of the many different high-level statements you choose to write - if
, switch
, for
, while
, etc. The issue is that modern computers work very well executing an unconditional instruction path, but when there's a decision point, they may slow down. Since you can't do anything interesting in computing without decision points (i.e., conditional branches), you might as well ignore the choice of high-level language construct.
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