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); } }

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?
java
Steve P.
source share