views:

96

answers:

3

Now, before you all jump on me and say "you're over concerned about performance," let it hereby stand that I ask this more out of curiosity than rather an overzealous nature. That said...

I am curious if there is a performance difference between use of the && ("and") operator and nested if statements. Also, is there an actual processing difference? I.e., does && always process both statements, or will it stop @ the first one if the first one fails? How would that be different than nested if statements?

Examples to be clear:

A) && ("and") operator

if(a == b && c == d) { ...perform some code fashizzle... }

versus B) nested if statements

if(a == b) {
    if(c == d) { ...perform some code fashizzle... }
}
+1  A: 

Like nested ifs, && is lazy.
The expression a && b will only evaluate b if a is truthful.

Therefore, the two cases should be completely identical, in both functionality and performance.

SLaks
You probably meant "will only evaluate b if a is truthful".
Gert G
+4  A: 

The performance difference is negligible. The && operator won't check the right hand expression when the left hand expression evaluates false. However, the & operator will check both regardless, maybe your confusion is caused by this fact.

In this particular example, I'd just choose the one using &&, since that's better readable.

BalusC
American Yak
Tikhon Jelvis
A: 

If you're concerned about performance, then make sure that a==b is more likely to fail than c==d. That way the if statement will fail early.

Gert G
Could someone shed some light on why I got a down vote on my answer?
Gert G
I don't know -- your suggestion seems fine to me so I've upvoted you.
Warren
My guess is the -1 was because it doesn't *reeaally* address the question, which was a curiosity about a particular point of Javascript, rather than general optimization.
Matchu
@Warren - Thanks. :) @Matchu - Well, it was already addressed by so many others in the thread. I just wanted to give him a hint on what to think about when it comes to IF statement design and performance. But I appreciate your comment. Thanks.
Gert G