6
public class Test {

    public static void main(String[] args) {

        int x = 150_000;

        long start = System.currentTimeMillis();
        for(int i = 0; i < x; i++) {            
            f1(i);
        }
        long end = System.currentTimeMillis();
        System.out.println((end - start) / 1000.0);
    }

    private static long f1(int n) {
        long x = 1;
        for(int i = 0; i < n; i++) {
            x = x + x;
        }
        return x;
    }
}

Can someone explain why setting x to 150_000 or 4_000_000 or even 2_000_000_000 doesn't change execution time of this loop?

8
  • 18
    Probably the compiler is smart enough to detect that nothing is happening in the loop so it optimizes out.
    – Tunaki
    Commented Oct 12, 2015 at 14:01
  • @Tunaki That would be my guess as well. f1 is returning some value, but that value is never used, and no other variables are being modified during the method. It would sense (to me at least) that the compiler completely ignores the call.
    – Mage Xy
    Commented Oct 12, 2015 at 14:03
  • 2
    @Pepo_rasta No. Underscores are now allowed in int and long literals (from Java 1.7 I think). Commented Oct 12, 2015 at 14:07
  • 4
    Possible duplicate of Java: how much time does an empty loop use? Commented Oct 12, 2015 at 14:09
  • 1
    For some reason these optimizations don't happen when you change i to be of type long. Commented Oct 12, 2015 at 14:12

1 Answer 1

10

During execution the JVM's just-in-time (JIT) compiler compiles the java bytecode (class format) to the native instruction set of your machine. The JIT performs several optimizations during compilation. In this case the JIT probably realised the followings (just guessing):

  • the f1() method does not have any visible side effects
  • the return value of the f1() call is not stored anywhere

therefore the JIT simply omitted the f1() invocation from the native code. It is possible that after removing the f1() call the entire for(int i = 0; i < x; i++) loop has been removed too (since it also doesn't change program semantics).

1
  • I love the JIT compiler, although sometimes, on really rare occasions you do need to account for it helping you out and optimizing your code. Especially when doing performance testing. Nice description +1.
    – Mark W
    Commented Oct 12, 2015 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.