JavaScript &&运算符与嵌套 if 语句:哪个更快?
现在,在你们跳到我面前说“你们过于关心表现”之前,先声明一下,我问这个问题更多是出于好奇,而不是出于过分热心的本性。也就是说......
我很好奇使用 && 之间是否存在性能差异。 (“and”)运算符和嵌套 if 语句。另外,是否存在实际的处理差异?即,&& 总是处理两个语句,或者如果第一个语句失败它会停止第一个语句吗?这与嵌套 if 语句有何不同?
需要明确的例子:
A) && (“and”) 运算
if(a == b && c == d) { ...perform some code fashizzle... }
符与 B) 嵌套 if 语句
if(a == b) {
if(c == d) { ...perform some code fashizzle... }
}
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... }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
性能差异可以忽略不计。当左侧表达式的计算结果为
false
时,&&
运算符不会检查右侧表达式。然而,&
运算符无论如何都会检查两者,也许您的困惑就是由这个事实引起的。在这个特定的示例中,我只选择使用
&&
的那个,因为这样可读性更好。The performance difference is negligible. The
&&
operator won't check the right hand expression when the left hand expression evaluatesfalse
. 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.如果您担心性能,请确保
a==b
比c==d
更容易失败。这样if
语句就会提前失败。If you're concerned about performance, then make sure that
a==b
is more likely to fail thanc==d
. That way theif
statement will fail early.与嵌套的
if
一样,&&
是惰性的。表达式
a && b
仅当a
为真时才会评估b
。因此,这两种情况在功能和性能上应该完全相同。
Like nested
if
s,&&
is lazy.The expression
a && b
will only evaluateb
ifa
is truthful.Therefore, the two cases should be completely identical, in both functionality and performance.
性能测试可能有助于澄清问题:http://jsperf.com/simey-if-vs- if
看起来两者之间的性能差异可以忽略不计;然而,正如 @Gert 提到的,尽早失败确实可以改善事情。
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.