-1

I'm working on a 2D engine in c++ and I know that an if statement costs less in terms of CPU usage than a switch statement; but, is the difference between a switch statement and an if statement negligible with modern PC and even on mobile porting, or must I avoid switch at all costs?

Tas
  • 7,023
  • 3
  • 36
  • 51
  • 2
    Hopefully you're not engaging in premature optimisation here. If in doubt, _measure_. If you can't measure a difference, you're probably looking for efficiency gains in the wrong place. – paddy Sep 01 '15 at 03:26
  • how do you know that `if` costs less than `switch case`? Normally a series of `if`is is much costlier than a `switch case` which is often simply a jump table – phuclv Sep 01 '15 at 03:45
  • I is what the teachers told about that, but it just confirm that : that kind of detail is to verify.. But they maybe right with very old compiler... Some of my teachers are there since more than 20 years, and teach exactly the same things than they did 2X years ago – JDany Hamel Sep 01 '15 at 06:10

1 Answers1

6

Optimisers have come a long way in the last couple decades. It's not normally worth guessing which of these things will make a difference - just write your code to be as clean, understandable and maintainable as possible, then run a profiler to get meaningful feedback to guide optimisation.

That said, if you feel you must guess at this - here's some general advice...

If you have one condition, then just use if/else (or a ? : pair where applicable).

If you have multiple conditions, and want control over the order in which they're tested because you have insight that lets you put the most probable branch at the top, then do so with if/[else], or - better - run a profiler and feed back branch prediction information to the optimiser when recompiling.

If you have a lot of values to test the same expression against, use a switch - the compiler's more likely to create some kind of dispatch table or binary branch tree that should out-perform a long, flat if/else if/... chain.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252