8

This question lead me to do some testing:

public class Stack
{
    public static void main(String[] args)
    {
        Object obj0 = null;
        Object obj1 = new Object();
        long start;
        long end;
        double difference;  
        double differenceAvg = 0;

        for (int j = 0; j < 100; j++)
        {
            start = System.nanoTime();

            for (int i = 0; i < 1000000000; i++)
                if (obj0 == null);

            end = System.nanoTime();
            difference = end - start;
            differenceAvg +=difference;
        }

        System.out.println(differenceAvg/100);
        differenceAvg = 0;

        for (int j = 0; j < 100; j++)
        {
            start = System.nanoTime();

            for (int i = 0; i < 1000000000; i++)
                if (null == obj0);

            end = System.nanoTime();
            difference = end - start;
            differenceAvg +=difference;
        }

        System.out.println(differenceAvg/100);
        differenceAvg = 0;

        for (int j = 0; j < 100; j++)
        {
            start = System.nanoTime();

            for (int i = 0; i < 1000000000; i++)
                if (obj1 == null);

            end = System.nanoTime();
            difference = end - start;
            differenceAvg +=difference;
        }

        System.out.println(differenceAvg/100);
        differenceAvg = 0;

        for (int j = 0; j < 100; j++)
        {
            start = System.nanoTime();

            for (int i = 0; i < 1000000000; i++)
                if (null == obj1);

            end = System.nanoTime();
            difference = end - start;
            differenceAvg +=difference;
        }

        System.out.println(differenceAvg/100);      
    }
}

enter image description here

Tangential to the other post, it's interesting to note how much faster the comparison is when the Object that we're comparing is initialized. The first two numbers in each output are when the Object was null and the latter two numbers are when the Object was initialized. I ran 21 additional executions of the program, in all 30 executions, the comparison was much faster when the Object was initialized. What's going on here?

Community
  • 1
  • 1
Steve P.
  • 14,489
  • 8
  • 42
  • 72

1 Answers1

3

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.

zch
  • 14,931
  • 2
  • 41
  • 49