Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my for loop execution time not changing?

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?

like image 398
RodionVanBeaver Avatar asked Oct 12 '15 13:10

RodionVanBeaver


1 Answers

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

like image 138
erosb Avatar answered Oct 30 '22 16:10

erosb