5

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

Community
  • 1
  • 1
Mike Warren
  • 3,796
  • 5
  • 47
  • 99
  • 6
    That's a very rare definition of 'expensive'! It's sort of like saying that $0.0001 is expensive. – Gabe Jun 03 '13 at 06:30
  • 1
    @Gabe: as always, that depends on the application. IF you need to spend $0.0001 several billion times, it does start to matter (although I agree it hardly ever is the majority of the cost). – Rody Oldenhuis Jun 03 '13 at 06:38
  • 2
    I prefer case statements because they're easier to read and reduces the chance of logic errors on the part of the programmer. No idea whether there's a difference in efficiency of the actual execution. – CaffeineConnoisseur Jun 03 '13 at 06:46
  • 1
    Related (perhaps Java specific): http://stackoverflow.com/questions/2086529/what-is-the-relative-performance-difference-of-if-else-versus-switch-statement-i – Rody Oldenhuis Jun 03 '13 at 06:49
  • 2
    Related (perhaps C++ specific): http://stackoverflow.com/questions/97987/advantage-of-switch-over-if-else-statement – Rody Oldenhuis Jun 03 '13 at 06:50
  • 1
    Related (perhaps C# specific): http://stackoverflow.com/questions/445067/if-vs-switch-speed – Rody Oldenhuis Jun 03 '13 at 06:51

1 Answers1

4

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.

Ross Patterson
  • 9,527
  • 33
  • 48