Efficiency of comparing Null / Object and Null / Null

This question forces 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 another post , it’s interesting to note how much faster the comparison happens when the Object we are comparing is initialized. The first two numbers on each output are when Object was null , and the last two numbers when initializing Object . I performed 21 additional program launches, in all 30 executions the comparison was much faster when Object initialized. What's going on here?

+8
java
source share
1 answer

If you move the last two cycles to the beginning, you will get the same results, so comparisons do not matter.

All about overclocking the JIT compiler. During the first 2 loops, java begins by interpreting the bytecode. After several iterations, it determines that the code path is β€œhot”, so it compiles it into machine code and removes loops that have no effect, so you basically measure the arithmetic of System.nanotime and double .

I'm not sure why the two loops are slow. I think that after finding two hot spots, he decides to optimize the whole method.

+3
source share

All Articles