- Home /
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
Thanks Dendro, that looks like what I was after. All the best Chris p.s. if you like put it up as an answer and I'll mark as correct. Thanks again.
Dendro's answer in comments above was considered the right answer. Chris
Answer by Joshua · Aug 25, 2011 at 08:14 AM
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.
thanks joshua. As opposed to nested if statements i was actually referring to multiple individual if's rather than nesting to else and else if's. I should have been more specific in fra$$anonymous$$g the question. The article link gives a good speed comparison though. Thanks again for responding. Best regards Chris.
Your answer
