SWITCH STATEMENT versus IF ELSE IF STATEMENT in C++

case, if-statement, switch-statement

Solution

A `switch` statement basically executes the same sort of comparison for every case: `var == a`, `var == b`, `var == c`, etc.

This page has details of how that's translated into assembly by a compiler, but there are essentially three "kinds" of switch statements:

- `switch` statements with contiguous `case` integers - such as `case 3: ... case 4: ... case 5: ...`. In these cases, the compiler can create a jump table -- a listing of addresses to jump to in a contiguous block of memory and just calculate the offset, find the address, and jump. This can be faster than `if-else if` type chains. (Slightly slow if there's only one case, of course.)

- `switch` statements with seemingly random `case` integers - such as `case 12: ... case 106: ... case 9: ...`. In these cases, the compiler will just build an `if-else if` chain, so it can't be faster than the `if-else if` type of code.

- `switch` statement with LOTS of seemingly random `case` integers - If there are a significant number, some compilers will build a binary search tree for all of the cases, so you have `O(log(n))` time to execute any particular branch, which should improve the performance of your code. (Significant depends on the architecture you're compiling on, since there's extra overhead with checking which branch of the tree you should follow or if you should now jump.)

This is a situation where you could outsmart the compiler, sometimes: If you know your cases can only be matched by some equation, like `3x+5`, then you could build an array of function pointers, calculate the index (`(caseNum - 5) / 3`), and then execute it Continuation-Passing Style (or if you want to drive people batty, do the same calculation and build an array of `goto` labels, and then jump spaghetti-style. Either way you'd get the optimal "contiguous case"-style assembly with `O(1)` branching time.

Problem

i have technical wondering here guys , switch statement performs faster ,that thing i know it but what i want to know is how does it perform faster than if & else if ? how can it find the controlExpression suitable case among all its cases directly? and if i supposed that it is written using if else if it self to run and find the suitable case ,so it shouldnt perform faster ,it would perform the same as if else if? so can u please answer me ? thanks in advance

Original source