Suppose I have an IF
condition :
if (A || B)
∧
|
|
left
{
// do something
}
Now suppose that A
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
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.
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.
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.
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.
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.