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
A
switchstatement 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:
switchstatements with contiguouscaseintegers – such ascase 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 thanif-else iftype chains. (Slightly slow if there’s only one case, of course.)switchstatements with seemingly randomcaseintegers – such ascase 12: ... case 106: ... case 9: .... In these cases, the compiler will just build anif-else ifchain, so it can’t be faster than theif-else iftype of code.switchstatement with LOTS of seemingly randomcaseintegers – If there are a significant number, some compilers will build a binary search tree for all of the cases, so you haveO(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 ofgotolabels, and then jump spaghetti-style. Either way you’d get the optimal “contiguous case”-style assembly withO(1)branching time.