using 'switch case' is generally faster than 'if else' but incase of only 2 cases if else is faster why?
please answer this was asked in a interview..
Printable View
using 'switch case' is generally faster than 'if else' but incase of only 2 cases if else is faster why?
please answer this was asked in a interview..
The switch statement only handles integral quantities.
Compilers may optimize the switch statement into a jump table
(see below).
An if-else-if ladder can handle any type, such as a string.
This construct is more difficult for a compiler to optimize.
A jump table is either a table of addresses (pointers) or
jump instructions. An index is used to access the appropriate
location, then an action is taken. This can be implemented
in C++ using an std::map of <key, function_pointer> or an
array of similar structures.
Thanks
--Suresh--
Switch statement is useful when we are having multiple options for the same variable but when we have to use mutiple conditions simultaneously then it would be better to use if else.
For dense case values compiler generates jump table, for sparse - binary search or series of if/else, so in worst case switch is as fast as if/else, but typically faster. Although some compilers can similarly optimise if/else.Hence switch has better performance than if-else.
Default can be anywhere. With if/else default case must be at the very end - after last else. In switch - default can be anywhere, wherever programmer finds it more appropriate.
First of all, never blindly assume that one method is always going to be faster than the other; code up both versions and [i]measure[/i] their relative performance.
Once you've made that measurement, if you see a result that's surprising to you, analyze the generated machine code; there may be something in the way the condition is structured that allows the compiler to generate more efficient code for the if statement as opposed to the switch.
Unless you are failing to meet a hard performance requirement, code for readability and maintainability [i]first[/i]; use a switch because it makes sense to do so, not because you think it will buy you a couple of cycles.