Search code examples
javaoptimizationcompiler-constructionboolean-logicboolean-expression

Boolean expressions optimizations in Java


Consider the following method in Java:

public static boolean expensiveComputation() {
    for (int i = 0; i < Integer.MAX_VALUE; ++i);
    return false;
}

And the following main method:

public static void main(String[] args) {
    boolean b = false;
    if (expensiveComputation() && b) {
    }
}

Logical conjunction (same as &&) is a commutative operation. So why the compiler doesn't optimize the if-statement code to the equivalent:

if (b && expensiveComputation()) {
}

which has the benefits of using short-circuit evaluation?

Moreover, does the compiler try to make other logic simplifications or permutation of booleans in order to generate faster code? If not, why? Surely some optimizations would be very difficult, but my example isn't simple? Calling a method should always be slower than reading a boolean, right?

Thank you in advance.


Solution

  • It doesn't do that because expensiveComputation() may have side effects which change the state of the program. This means that the order in which the expressions in the boolean statements are evaluated (expensiveComputation() and b) matters. You wouldn't want the compiler optimizing a bug into your compiled program, would you?

    For example, what if the code was like this

    public static boolean expensiveComputation() {
            for (int i = 0; i < Integer.MAX_VALUE; ++i);
            b = false;
            return false;
    }
    
    public static boolean b = true;
    public static void main(String[] args) {
            if (expensiveComputation() || b) {
            // do stuff
            }
    }
    

    Here, if the compiler performed your optimization, then the //do stuff would run when you wouldn't expect it to by looking at the code (because the b, which is originally true, is evaluated first).