From what I have read I can summarize,
if/elseif
(?)Consider a case where I have 300+ switch cases. I know an if/elseif
in this scene will be a mess.
But I want to know how will a switch
case perform in such a scene?
if/elseif
- switch
comparison apart from actually writing the code and using a profiler? I have tried compiling a small .c
file with switch case using gcc 4.8.1
-S
switch and it looks like a jump table is created.Where do I go from here?if/elseif
in such scenariosI am primarily interested in C/C++ specific details
The compiler might decide to use a jump table and make a huge improvement in the case of 300+.
Compilers do make optimizations over branches using various techniques like decision trees .
The more easy is for a compiler to understand the code, the better. And the switch statement is more readable for the compiler as well.
Think about the else if from a compilers point of view . It would look like an arrowhead :
- if - else - else - else - else
You need to evaluate each previous if in order to get to the correct else .
However a Switch looks more like a block :
- case - case - case - case
So the compiler can sometimes determine where to go directly.
For your bullet questions :
it is scalable. It's easy to be written by the developers and if the compiler uses jump tables adding more cases won't affect.
it's up to the compiler to decide what to use. It might choose to not optimize it at all (but most likely jump tables).
You can run a loop and meassure times by hand maybe ?
It's always better to use switch. The worst case scenario the switch will act just as an if/else .
Compilers for most of the low end processors(Mostly Used in Embedded Systems) compiler do not always generate jump table for switch case.
If the case variables are in sequence (e.g 1,2,3,4....) then jump table implementation of switch case is preferred by compiler ,but for random sequence of case variable(e.g. 12,344,565,1,5...) compiler generates same code as generated in case of if-else code.
Sometimes,due to this developers land into trouble when adding a random case variable into already OK code may change the whole implementation of the that section of code which can result major change in code execution timing and code size. These are most concerning point to a embedded developer.
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