Switch slower than if-else | Sololearn: Learn to code for FREE!

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?

3/26/2018 2:26:16 AM

Desmond Sackey

1 Answer

New Answer

+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.