Why doesn't my cycle time for cycle change?

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 does not change the execution time of this cycle?

+6
source share
1 answer

At run time, the JVM JVM compiler compiles java bytecode (class format) into its own set of commands on your computer. JIT performs several optimizations at compile time. In this case, JIT probably understood the following (just guessing):

  • The f1() method has no visible side effects
  • call return value f1() not stored anywhere

so JIT just missed the call to f1() from native code. Perhaps after deleting the call to f1() entire for(int i = 0; i < x; i++) loop for(int i = 0; i < x; i++) also deleted (since it also does not change the semantics of the program).

+10
source

All Articles