Boolean expression optimization in Java

Consider the following methods in Java:

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

The following main methods:

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

The logical connection (the same as & &) is a communicative operation So why doesn't the compiler optimize the if statement code into equivalent code:

if (b && expensivecomputation()) {
}

Which has benefits of using short circuit evaluation?

In addition, does the compiler try to make other logical simplifications or permutations of Boolean values to generate faster code? If not, why? Of course, some optimization will be very difficult, but my example is not simple? Calling methods should always be slower than reading Boolean values, right?

Thank you first

Solution

It won't do this because expensivecomputation () may have side effects, changing the state of the program This means that it is important to evaluate the order of expressions (expensivecomputation () and b) in Boolean statements You don't want the compiler to optimize errors into the compiled program, do you?

For example, if the code is 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 performs optimization, it will run / / do stuff when you don't want it to view the code (because B, it is true at first, it is evaluated first)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>