Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is switch just as bad as if?

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)?

like image 369
Mike Warren Avatar asked Oct 04 '22 23:10

Mike Warren


1 Answers

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.

like image 191
Ross Patterson Avatar answered Oct 12 '22 10:10

Ross Patterson