As @MariusDanila noted in his comment, this is because the JIT is kicking.
To verify this, you can run java with the -Xint
option, which forces it to run the mode only for interpretation, so nothing is compiled into its own code (and, of course, there are no optimizations performed with this native code).
So here is what I got java:
"Elapsed time: 4.175 msecs" 20000 "Elapsed time: 2.548 msecs" 20000 "Elapsed time: 7.746 msecs" 20000 "Elapsed time: 1.919 msecs" 20000 "Elapsed time: 1.72 msecs" 20000
Note that here the time has actually increased for the third run. I assume this is due to compilation happening at the same time. Whereas with -Xint
:
"Elapsed time: 31.463 msecs" 20000 "Elapsed time: 30.844 msecs" 20000 "Elapsed time: 30.643 msecs" 20000 "Elapsed time: 29.972 msecs" 20000 "Elapsed time: 30.617 msecs" 20000
As you can see from the second example, there is no acceleration.
This is why Rule 1 for micro-detection should always exclude warm-up time from your measurements.
source share