- Home /
Single line if statement with many conditions or several single-conditioned if statements
I apologize that this is not exactly Unity related, but I could not find any information on this elsewhere.
I have been wondering for a long time now what is the best way to use if statements. You can see what I mean by that below.
A single line if statement(contains several conditions):
if(X && Y && W && Z && G){
Execute();
}
And Many statements inside a statement.
if(X){
if(Y){
if(W){
if(Z){
if(G){
Execute();
}
}
}
}
}
In the end they all do the same thing I suppose, but obviously the first example looks a bit more neat than the latter, but are there any performance benefits(or any benefits for that matter) using either of these two examples?
Thank you,
Yours faithfully.
Answer by whydoidoit · May 31, 2012 at 06:39 PM
An if with multiple parts separated by && or || only evaluates subsequent terms if it needs to - so there is no performance difference and they are equivalent.
i.e. X && Y
only checks Y if X is true. X || Y
only checks Y if X is false
I would strongly counsel against anything that had that much indentation - you'll tie yourself in knots trying to work out what is going on.
Now that I think about it you stand correct. Thanks for the info!