为什么if语句中的表达式顺序很重要 [英] Why is order of expressions in if statement important

查看:103
本文介绍了为什么if语句中的表达式顺序很重要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个IF条件:

if (A || B) 
    ∧
    |
    |
   left
{ 
   // do something  
}

现在假设AB更可能收到真实值,为什么我要关心左边的是哪个?

Now suppose that A is more likely to receive a true value then B , why do I care which one is on the left ?

如果将它们都放在IF括号中,那么我(作为代码的程序员)就知道双方都需要.

If I put both of them in the IF brackets , then I know (as the programmer of the code) that both parties are needed .

问题是,我的教授在他的演讲笔记上写道,我应该在左侧放置更可能的变量以接收真值".

The thing is , that my professor wrote on his lecture notes that I should put the "more likely variable to receive a true" on the left .

有人可以解释一下好处吗?好吧,我把它放在左边...我正在获得什么?运行 ?

Can someone please explain the benefit ? okay , I put it on the left ... what am I gaining ? run time ?

推荐答案

这不仅仅是在左侧选择最可能的条件.您也可以在左侧设置一个安全门卫,这意味着您只能下一个订单.考虑

Its not just about choosing the most likely condition on the left. You can also have a safe guard on the left meaning you can only have one order. Consider

if (s == null || s.length() == 0) // if the String is null or empty.

您不能在此处交换订单,因为第一个条件可以防止第二个条件抛出NPE.

You can't swap the order here as the first condition protects the second from throwing an NPE.

类似地,您可以拥有

if (s != null && s.length() > 0) // if the String is not empty

||选择最可能为true或为&&选择最可能为false的原因是微优化,以避免在第二个表达式中求值的成本.是否转化为可衡量的性能差异尚待商de.

The reason for choosing the most likely to be true for || or false for && is a micro-optimisation, to avoid the cost of evaluated in the second expression. Whether this translates to a measurable performance difference is debatable.

这篇关于为什么if语句中的表达式顺序很重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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