Java中的布尔表达式优化 [英] Boolean expressions optimizations in Java

查看:246
本文介绍了Java中的布尔表达式优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中考虑以下方法:

Consider the following method in Java:

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

以及以下主要方法:

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

逻辑合取(与&& ;;相同)是交换运算.那么为什么编译器没有将if语句代码优化为等效代码:

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()) {
}

具有使用短路评估的优点?

此外,编译器是否会尝试对布尔值进行其他逻辑简化或置换以生成更快的代码?如果没有,为什么?当然,某些优化将非常困难,但是我的例子并不简单吗?调用方法应该总是比读取布尔值慢,对吧?

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?

谢谢.

推荐答案

之所以不能这样做,是因为costableComputation()可能会产生副作用,从而改变程序的状态.这意味着布尔表达式中的表达式(expensiveComputation()和b)的求值顺序很重要.您不想让编译器在已编译的程序中优化错误,对吗?

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

在这里,如果编译器执行了优化,则//do stuff将在您不希望通过查看代码来执行时运行(因为最初为b的b首先被求值).

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).

这篇关于Java中的布尔表达式优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆