Javascript && operator versus nested if statements: what is faster?
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 f开发者_开发知识库ashizzle... }
}
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.
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.
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.
A peformance test might help clear things up: http://jsperf.com/simey-if-vs-if
Seems the performance difference is incredibly negligable between the two; However as @Gert mentioned, failing early really improves things.
加载中,请稍侯......
精彩评论