0

Switch slower than if-else

I tried replacing an if-else statement code with switch after learning this technique, but it was visible clear that my computer was slower an processing the switch statement. Is this normally true?

26th Mar 2018, 2:26 AM
Desmond Sackey
Desmond Sackey - avatar
1 Réponse
+ 3
It shouldn't be slower. On average, your if else statements must perform half of the tests one at a time. Whereas, the switch uses a table lookup to jump directly to the correct case. I usually assume that 5 conditions in the ifs is more expensive than the corresponding switch. However, that was based non-optimization compilers. Todays compilers should be smart enough to pick whichever code is faster regardless of what method you code.
26th Mar 2018, 2:40 AM
John Wells
John Wells - avatar