Why is order of expressions in if statement important

后端 未结 9 2015
无人共我
无人共我 2021-01-05 03:01

Suppose I have an IF condition :

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

Now suppose that A

9条回答
  •  北海茫月
    2021-01-05 03:42

    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.
    

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

    Similarly you can have

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

    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.

提交回复
热议问题