Javascript && 运算符与嵌套 if 语句:哪个更快?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3126201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript && operator versus nested if statements: what is faster?
提问by arxpoetica
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 && alwaysprocess bothstatements, or will it stop @ the first one if the first one fails? How would that be different than nested if statements?
我很好奇在使用 &&(“and”)运算符和嵌套 if 语句之间是否存在性能差异。另外,是否有实际的处理差异?即,&& 是否总是处理两个语句,或者如果第一个失败,它会停止@第一个?这与嵌套的 if 语句有何不同?
Examples to be clear:
举例说明:
A) && ("and") operator
A) && ("and") 运算符
if(a == b && c == d) { ...perform some code fashizzle... }
versus B) nested if statements
与 B) 嵌套 if 语句
if(a == b) {
if(c == d) { ...perform some code fashizzle... }
}
采纳答案by BalusC
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 bothregardless, maybe your confusion is caused by this fact.
性能差异可以忽略不计。该&&运营商将不检查的右手表达左手表达式的计算结果时false。但是,&运营商无论如何都会检查两者,也许您的困惑是由这个事实造成的。
In this particular example, I'd just choose the one using &&, since that's better readable.
在这个特定的例子中,我只选择使用 的&&那个,因为它更好读。
回答by Gert Grenander
If you're concerned about performance, then make sure that a==bis more likely to fail than c==d. That way the ifstatement will fail early.
如果您担心性能,请确保它a==b比c==d. 这样if语句就会提前失败。
回答by simey.me
A peformance test might help clear things up: http://jsperf.com/simey-if-vs-if
性能测试可能有助于解决问题: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.
两者之间的性能差异似乎可以忽略不计;然而,正如@Gert 提到的,早期失败确实会改善事情。
回答by SLaks
Like nested ifs, &&is lazy.
The expression a && bwill only evaluate bif ais truthful.
就像嵌套的ifs,&&是懒惰的。
该表达式a && b仅b在 a为真时才进行评估。
Therefore, the two cases should be completely identical, in both functionality and performance.
因此,这两种情况在功能和性能上都应该完全相同。

