为什么if语句中的表达式顺序很重要

编程入门 行业动态 更新时间:2024-10-11 21:28:17
本文介绍了为什么if语句中的表达式顺序很重要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个IF条件:

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

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

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语句中的表达式顺序很重要

本文发布于:2023-11-02 18:20:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1553086.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:很重要   表达式   语句   顺序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!