Boolean expressions optimizations in Java

前端 未结 5 749
[愿得一人]
[愿得一人] 2021-01-14 17:56

Consider the following method in Java:

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


        
5条回答
  •  北恋
    北恋 (楼主)
    2021-01-14 18:34

    Because expensiveComputation() may have side-effects.

    Since Java doesn't aim to be a functionally pure language, it doesn't inhibit programmers from writing methods that have side-effects. Thus there probably isn't a lot of value in the compiler analyzing for functional purity. And then, optimizations like you posit are unlikely to be very valuable in practice, as expensiveComputation() would usually be required to executed anyway, to get the side effects.

    Of course, for a programmer, it's easy to put the b first if they expect it to be false and explicitly want to avoid the expensive computation.

提交回复
热议问题