JS switch vs multiple if's efficiency?

Hi All,
Is there any difference in the efficiency of code execution when using multiple if statements as opposed to making a single switch statement?

It’s on an OnTriggerEnter(hit : Collider) function to try and capture the multiple collision possibilities for a projectile. Thank you.

Cheers Chris

I can't really answer as I can't explain in detail what I'm about to say but.. It depends on the nature of the logic you want to implement. If it's consistently going to be traversed over the duration of your game (and if there's really a LOT of conditions there..) you may want to try doing a switch statement. Switch statements have extra optimization that is done in the background when compared to if-else blocks.

–

Here's a study that compares the execution time of both an if-else block and a switch statement. You'll notice that it would generally take a LOT of iterations for the difference to be even obvious. http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx

–

1 Answer

1

Switch statements are indeed more efficient, but “Switch statements have extra optimization that is done in the background when compared to if-else blocks.” isn’t really the reason.

The reason is that the expression is evaluated once and then the side effects get executed. With several if else if else statements each if gets checked one by one until one returns true and gets executed.