Java如何处理IF语句和效率 [英] How Java handles IF statements and efficiency

查看:223
本文介绍了Java如何处理IF语句和效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是好奇Java在 if 语句时的实际工作原理。 (注意:当我说下面的组件时,我指的是语句检查的个别部分,例如 a b c

I'm just curious about how Java actually works when it come to if statements. (Note: when I say "component" below I mean the idividual parts checked by the statement, e.g. a, b, c)

哪个在计算方面更有效?

Which is more efficient in terms of calculations?

if (a && b && c) { do stuff }

if (a) {
  if (b) {
    if (c) {
    do stuff }
  }
}

我问的原因是因为Java在第一个版本中的作用很重要。它是检查语句中的每一件事还是检查 a ,如果它是 false 然后取消检查其余的语句?

The reason why I ask is because it's important what Java does in the first version. Does it check every single thing in the statement or does it check a and if it is false then cancel checking the rest of the statement?

如果是这种情况,那么将组件最有可能失败作为语句中的第一个组件是有意义的。

If this is the case then it makes sense to put the component most likely to fail as the first component in the statement.

如果每次检查整个语句,那么将组件拆分成一堆不同的语句更有意义,如第二个例子所示。

If the whole statement is checked every time then it makes more sense to split the components into a bunch of different statements, as in the second example.

推荐答案

在Java中,&& || 保证短路:操作数从左到右进行评估,一旦确定结果,评估就会停止。

In Java, && and || are guaranteed to short-circuit: the operands are evaluated left-to-right, and the evaluation stops as soon as the result is known with certainty.

来自 JLS


&& 运算符类似于& (§15.22.2),但仅当其左手操作数的值为 true 时才计算其右手操作数。它是语法上的左关联(从左到右分组)。

The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true. It is syntactically left-associative (it groups left-to-right).

|| 运算符类似于 | (§ 15.22.2),但仅在其左侧操作数的值为false时才计算其右侧操作数。它在语法上是左关联的(它从左到右分组)。

The || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. It is syntactically left-associative (it groups left-to-right).

这意味着你问题中的两个代码片段完全相同。

This means that the two code snippets in your question are exactly equivalent.

这篇关于Java如何处理IF语句和效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆