Boolean expressions optimizations in Java

前端 未结 5 796
[愿得一人]
[愿得一人] 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:29

    The compiler will optimize this if you run the code often enough, probably by inlining the method and simplifying the resulting boolean expression (but most likely not by reordering the arguments of &&).

    You can benchmark this by timing a loop of say a million iterations of this code repeatedly. The first iteration or two are much slower than the following.

提交回复
热议问题