This question lead me to do some testing:
public class Stack
{
public static void main(String[] args)
{
Object obj0 = null;
Object obj1 =
If you move last two loops to the beginning you will get the same results, so comparisons are irrelevant.
It's all about JIT compiler warm-up. During the first 2 loops java
starts with interpreting bytecode. After some iterations, it determines that code path is "hot", so it compiles it to machine code and removes the loops that have no effect, so you are basically measuring System.nanotime
and double
arithmetic.
I'm not really sure why two loops are slow. I think that after it finds two hot paths it decides to optimize entire method.