Boolean expressions optimizations in Java

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

    Actually, some compilers can optimise programs like the one you suggested, it just has to make sure that the function has no side-effects. GCC has a compiler directive you can annotate a function with to show that it has no side-effects, which the compiler may then use when optimizing. Java may have something similar.

    A classic example is

    for(ii = 0; strlen(s) > ii; ii++) < do something >

    which gets optimized to

    n = strlen(s); for(ii = 0; n > ii; ii++) < do something >

    by GCC with optimization level 2, at least on my machine.

提交回复
热议问题