In a book I found these statements......
"A switch with 10 cases would work faster than an equivalent if-else ladder. Also, a switch with 2 cases would work slower than if-else ladder.Why?"
Will anyone please explain the above statement?
Well, as CommonTater already mentioned, this statement isn't quite as accurate, it highly depends on both the compiler implementation for at least the switch construct as well as the statements used in both the switch and if-else.
On simple numeric statements, a clever compiler might generate a lookup table, which can process each selection within the switch construct with the same speed. But then a clever compiler, doing a fair amount of optimization, might end up doing the same thing for a chain of if-else statements and not a "compare and branch" chain down the whole list of different else's, where it would take more time to evaluate the comparison each time...
This is one of those cases where IMHO it pays if someone knows assembly language, knows how a processor can actually execute such higher level instructions and what might be a faster option or not.
And on the other side, it is also true what CommonTater said about maintainability of code. A neatly formatted switch construct might be easier to understand and expand than several pages of chained if-else statements. And with only two options in a switch statement and only a short conditionally executed code block for each, a properly formatted if-else might be easier to understand that the switch statement. Or in some case, it might even be better to use the otherwise dreaded
"
x = (
<condition> ?
a :
b )
Ralf