From the point of view of optimizing the code run time, is there a thumb rule for where to use "nested if" statement and when to use "switch case" statements ?
-
Switch is generally a replacement for if/elseif/elseif kind of patterns rather than nested if - is that what you meant? – Jeff Foster Jun 02 '11 at 07:37
-
possible duplicate of [Why Switch/Case and not If/Else If?](http://stackoverflow.com/questions/1028437/why-switch-case-and-not-if-else-if) – Bo Persson Jun 02 '11 at 13:16
-
As tofutim said, choose the easiest to read as there is no optimization differences. Too many nested statements just makes things messy to read. – wilbomc Jul 12 '13 at 02:49
3 Answers
I doubt you will ever find a real-life application where the difference between a nested if and a switch case is even worth measuring. Disk access, web access, etc. take many many orders of magnitude more time.
Choose what is easiest to read and debug.
Also see What is the difference between IF-ELSE and SWITCH? (possible duplicate) as well as Advantage of switch over if-else statement. Interestingly, a proponent of switch writes
In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.
In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decission tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).
-
1The compiler can treat an if/else chain the same way it can a switch, as long as the semantics of the program allow it. There is no way to be sure the compiler isn't clever enough to raise worries about Skynet. If you have to care, then a) measure and b) inspect the output of particular compilers you care about. The general answer is what tofutim siad: "Choose what is easiest to read and debug.". – Jun 02 '11 at 07:50
If you have more than 2-3 comparisons then "switch" else "if"
try to apply some patterns before you go to switch like strategy...

- 4,408
- 4
- 38
- 65
I don't believe it will make any difference for a decision structure that could be implemented using either method. It's highly likely that your compiler would produce the same instructions in the executable.

- 188
- 1
- 3
- 10