- Home /
C# if-statement optimization
Just a short question about optimizing. Say I have three conditions for example the player must be alive, have enough ammunition, and press the firekey. Would it be more effective to write it all in one statement or make them separate? Maybe I'm accessing a variable from antoher script in the if-statement then it must be more effectiev to at least put that one in a second statement right?
Answer by Owen-Reynolds · Sep 15, 2012 at 05:11 PM
It's the same because of Lazy Eval. Say you have `if(a>0 && b>0)` and `a` is negative. The computer won't even check `b` (*), since the IF is already 100% false. Put another way, all ifs with ands/ors auto get turned into separate ifs anyway.
One trick, which also make the program easier to read, is to put the "you can stop now" conditions first. Say that berserk wounded orcs charge you. If orcs are rarely berserk, check for it first: `if(berserk && HP0)` is false.) There's enough stuff like this going on that worrying about little speed fixes isn't worth it.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Game optimization using .SetActive() slowing down game. 0 Answers
How to network a large map with 4000+ movable objects using Photon Unity Networking? 1 Answer
How to render severals cameras at differents Frame Rate ? 2 Answers