Why is order of expressions in if statement important
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.
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.