java - Why is the first nested iteration faster than subsequent ones? -


test application:

public class main {      private static long = 0;      public static void main(string[] args) {         (int = 0; < 5; i++) {             long start = system.currenttimemillis();             (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 first nested iteration considerably faster subsequent ones whenever run program.

why 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 copy-paste outer loop right below first one:

public class main {      private static long = 0;      public static void main(string[] args) {         (int = 0; < 5; i++) {             long start = system.currenttimemillis();             (long j = 0; j < 5000000000l; j++) a++;             system.out.println(system.currenttimemillis() - start);         }          system.out.println("----");          (int = 0; < 5; i++) {             long start = system.currenttimemillis();             (long j = 0; j < 5000000000l; j++) a++;             system.out.println(system.currenttimemillis() - start);         }          system.out.println("\na = " + a);     } } 

then again first iteration fastest in both outer loops:

2587 3736 3736 3734 3732 ---- 2560 3737 3734 3735 3740 

even in first example, expect first iteration slower, because of warm-up time (initialization, jit optimizations, etc), described in answers question @mureinik kindly pointed to, opposite.

edit 2

when increase limit j variable adding 0 (ten times), difference more 10 seconds:

25747 38637 37767 38104 38690 ---- 27951 38780 39035 37962 37931 

it seems constant ratio of 2.6/3.7.


Comments