Why is order of expressions in if statement important

不羁岁月 提交于 2020-04-29 12:14:29

问题


Suppose I have an IF condition :

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

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 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 ?


回答1:


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.




回答2:


I put it on the left ... what am I gaining ? run time ?

Because || operator in C++ uses short-circuit evaluation.
i.e: B is evaulated only if A is evaluated to a false.

However, note that in C++ short-circuit evaluation is guaranteed for "built in" data types and not custom data types.




回答3:


As per javadoc

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed

So, if true statement comes first in the order, it short-circuits the second operand at runtime.




回答4:


If the expression on the left is true, there is no need to evaluate the expression on the right, and so it can be optimized out at run time. This is a technique called short-circuiting. So by placing the expression more likely to be true on the left, we can expect our program to perform better than if it were the other way around.




回答5:


You should place the condition that is more likely to be true first because that will cause the if statement to short-circuit. Meaning it will not evaluate the rest of the if statement because it will already know the answer is true. This makes code more efficient.

This is especially useful when your if statement is evaluating expensive things:

if(doExpensiveCheck1() || doExpensiveCheck2()) { }

In this case cause the checks are expensive it is in your benefit to place the most likely check first.




回答6:


In many cases there is no practical difference apart from a tiny performance improvement. Where this becomes useful is if your checks are very expensive function calls (unlikely) or you need to check things in order. Say for example you want to check a property on something and to check if that something is nil first, you might do something like:

If (a != nil && a.attribute == valid) {}




回答7:


Yes exactly, you're gaining runtime, it won't seem much for one operation, but you have to keep in mind that operations will get repeated millions of times

Why perform two evaluations when one is enough is the logic




回答8:


At runtime if(a||b) will test a first, if a is true it will not waste time testing b therefor the compiler will be 1 execution ahead. Therefore if a is more likely to be true than b this test is also likely to cut 1 line. The total number of lines not executed is tiny on a single line but it’s huge if the statement is nested in a loop of some sort(for,while ,recession or database related queries ). Eg per say we have 1million mins to test data in a database at 1 minute per record (30sec for condition A and 30 sec for condition B). Let A have 80% chances to be true and B have 20% chances to be true. The total time needed if you put A first is 600-000hrs yet it’s 900-000hrs if you put B first.if A is tested first[(0,8*1millions hours)*0,5mins+(0,2*1million hours)*1min]===6000-000hrs : if B is tested first [(0,2*1million hours)*0,5mins+(0,2*1million hours)*1min]===9000-000hrs. However you will notice the difference is less significant if the probability of A becoming true is closer to that of B.




回答9:


public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        Integer a = null;
        Integer b = 3;
        Integer c = 5;

        if(a != null && a == 2){
            System.out.println("both");
        }else{
            System.out.println("false");
        }
    }
}

Hello World
false



来源:https://stackoverflow.com/questions/12119240/why-is-order-of-expressions-in-if-statement-important

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!