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?
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):
f1()
method does not have any visible side effectsf1()
call is not stored anywheretherefore 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With