To be precise, having a switch instead of many if/then/else allows the compiler to easily optimize your program (usually via a jumplist), whereas if/then/else optimization will result in a harder optimization.
The more your compiler knows what you want to do, the better it can optimize it.
It makes no difference whatsoever to the compiler.
Choose the construct that is more readable and maintainable (more programmer efficient).
Leave low level optimization to the compiler; it does that a lot better than most programmers.
Focus on optimisations that the compiler can't do for us - choice of data structures, algorithms, and other high level constructs.
Reason, why binary tree can't be build for if/else it that it can break logic.
We are talking about perfomance (and choice) of switch/if-else in some case. In your case you simply cannot replace it with switch as-is.
What about comparing x with 1000000000?
Try it. Clang builds same code for both switch and if-else: something that looks like binary tree. (Although there is possibility to build jump table for it, compilers are either not smart enough or decide that testing/conversion overhead is not worth it)
> after the if condition is met, does that mean that it will still check vs. else-if conditions?
The observable behaviour of the program would be as-if it first checked the if condition, and if that was met, the else-if conditions were not checked.
The compiler is allowed to rewrite the code as long as the observable behaviour of the rewritten code is indistinguishable from the observable behaviour of the original code. http://en.cppreference.com/w/cpp/language/as_if
int foo( int a )
{
int b = 0 ;
if( a < 7 ) b += 5 ;
elseif( a > 9 ) b += 6 ;
elseif( a == 7 ) b += 5 ;
elseif( a > 10 ) b += 6 ;
elseif( a == 8 ) b += 5 ;
elseif( a == 11 ) b += 6 ;
elseif( a == 9 ) b += 5 ;
else b += 6 ;
if( a < 7 ) b += 15 ;
elseif( a > 9 ) b += 26 ;
elseif( a == 7 ) b += 15 ;
elseif( a > 10 ) b += 26 ;
elseif( a == 8 ) b += 15 ;
elseif( a == 11 ) b += 26 ;
elseif( a == 9 ) b += 15 ;
else b += 26 ;
return b ;
}
a compiler is allowed to generate code as if foo() was: int foo( int a ) { return a > 9 ? 32 : 20 ; }
In addition, choose the language construct that most closely reflects the logic of your algorithm. If the logic is "do X, Y, or Z depending on the value of k" then a switch statement would make sense. This helps another programming understand your code.
Consider using arrays if possible (more often than you might think) and speed is an issue. Extra code for boundary checks is negligible for large case statements.
1 2 3 4 5 6
int lut[] = {5,22,0,7,1,100};
int foo( int a )
{
return lut[a];
}