JavaScript &&运算符与嵌套 if 语句:哪个更快?

发布于 2024-09-07 00:30:09 字数 487 浏览 7 评论 0原文

现在,在你们跳到我面前说“你们过于关心表现”之前,先声明一下,我问这个问题更多是出于好奇,而不是出于过分热心的本性。也就是说......

我很好奇使用 && 之间是否存在性能差异。 (“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

澉约 2024-09-14 00:30:09

性能差异可以忽略不计。当左侧表达式的计算结果为 false 时,&& 运算符不会检查右侧表达式。然而, & 运算符无论如何都会检查两者,也许您的困惑就是由这个事实引起的。

在这个特定的示例中,我只选择使用 && 的那个,因为这样可读性更好。

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.

不再见 2024-09-14 00:30:09

如果您担心性能,请确保 a==bc==d 更容易失败。这样 if 语句就会提前失败。

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.

各自安好 2024-09-14 00:30:09

与嵌套的 if 一样,&& 是惰性的。
表达式a && b 仅当 a 为真时才会评估 b

因此,这两种情况在功能和性能上应该完全相同。

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.

沩ん囻菔务 2024-09-14 00:30:09

性能测试可能有助于澄清问题: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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文