Test application:
public class Main {
private static long a = 0;
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
long start = System.currentTimeMillis();
for (long j = 0; j < 5000000000L; j++) a++;
System.out.println(System.currentTimeMillis() - start);
}
System.out.println("\na = " + a);
}
}
The output:
2600
3739
3735
3734
3742
I noticed that the first nested iteration is considerably faster than subsequent ones whenever I run the program.
Why is it so?
Java version:
java version "1.8.0_74"
Java(TM) SE Runtime Environment (build 1.8.0_74-b02)
Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode)
EDIT
If I copy-paste the outer loop right below the first one:
public class Main {
private static long a = 0;
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
long start = System.currentTimeMillis();
for (long j = 0; j < 5000000000L; j++) a++;
System.out.println(System.currentTimeMillis() - start);
}
System.out.println("----");
for (int i = 0; i < 5; i++) {
long start = System.currentTimeMillis();
for (long j = 0; j < 5000000000L; j++) a++;
System.out.println(System.currentTimeMillis() - start);
}
System.out.println("\na = " + a);
}
}
then again the first iteration is the fastest in both outer loops:
2587
3736
3736
3734
3732
----
2560
3737
3734
3735
3740
Even in the first example, I would expect the first iteration to be slower, because of warm-up time (initialization, JIT optimizations, etc), as described in the answers for question which @Mureinik kindly pointed to, but it is the opposite.
EDIT 2
When I increase the limit for j
variable by adding another zero to it (ten times), the difference is more than 10 seconds:
25747
38637
37767
38104
38690
----
27951
38780
39035
37962
37931
It seems to be a constant ratio of about 2.6/3.7
.