which is the more efficient if statement

Which of the two if statements is the more efficient one?

If these boolean statement were instead a more costly checking of some value which is the better way to go?

Or are these equally as efficient?

boolean1 = true;
boolean2 = true;
boolean3 = false;
boolean4 = true;


if(boolean1==true && boolean2==true && boolean3==true && boolean4==true){

// OR



They are the same. The first uses lazy-evaluation, quitting after the 1st false, same as the 2nd.

But even if one was a tiny bit faster than the other, it’s almost always better to just write clear, easy to read code. It’s super-hard to know what runs faster (ex: a=3*4; is just as fast as a=12;.) You’ll likely make a dozen small changes later on. And most speed problems are big mistakes (random access on a list, AI every frame … .)

I put them into a simple script and over time looked to see if there was any difference to collective frame time, separately of course. Found nothing, except they both bizarrely chewed up the Debug.Log and ground everything down proper slow :stuck_out_tongue: - (deffo not a computer issue! It’s quick enuff)

Based on Owens Answer - [Citation Needed]

They are the same. The first uses
lazy-evaluation, quitting after the
1st false, same as the 2nd.

For the fastest usage of Case 1 :
For any condition More Likely to be false, place it to the left of the if therefore cutting out unnecessary checking.

Case 2 is technically different as at each stage you get the option to run code and branch each check. However, if all 4 need to be true to Run ExpensiveFunction again, place conditions more likely to become false in if statement 1.

(If Owen is incorrect, entropy is only possible in case 2.)

This is Entropy (I believe) and statistically guaranteed to prove faster if your probability-logic holds true.

In a nutshell, if something is more likely to occur more often you need less information to define it.

On paper, Statement 2 has fewer operations. But you never know what a compiler/optimizer is going to do with code like this.

Quadruply nested ANYTHING is horribly ugly though. I avoid it on principle.

In the case of just checking a bunch of booleans, the difference between these two structures is negligible. Optimization in this situation would really be dependent on how processor intensive a method that is say returning a boolean or something of the like is happening, in which case you would want to order your checks in the most efficient manner.

For something like this, I would go with statement one as I find it to be more human readable. In some cases, you have to nest the IF statements because of additional logic, but in terms of a rudimentary question such as this, either way is fine.