-1

Consider this code snippet

import java.util.Date;

  class Test {
     public static void main(String[] args) {

    Date date = null;

    long startTime = System.currentTimeMillis();

    if(date == null) {
        System.out.println("null == date");
    }else {
        System.out.println("date found "+date);
    }

      long stopTime = System.currentTimeMillis();
      long elapsedTime = stopTime - startTime;
      System.out.println(elapsedTime);
    }
}

In if condition I used date==null I wanted to know is there there any reduction in time complexity or vice versa if I choose to write null==date

PS- for both the condition my code is producing output as 0 but what if the code is complex and has heavy operations ?

Chaitanya Uttarwar
  • 318
  • 2
  • 6
  • 13

1 Answers1

1

date == null and null == date is almost exact equivalent.

In your specific case there no difference between them neither in speed nor in observed behavior.

You got 0 because modern computer is really fast and it is took less then millisecond to perform that calculation.

PS: If you really want to measure how long does it take you have to execute it hundreds of thousands times and divide measured time to count of execution.

PPS: Micro benchmark is not that easy in Java because you have take a lot of things into account, like JVM internal behavior, compiler optimization, GC, JIT and maybe something more.

EDIT I was wrong they are complete equivalent because this code will be compiled to use IFNONNULL instruction.

talex
  • 17,973
  • 3
  • 29
  • 66
  • 1
    It makes no difference until introducing multiple conditions. which then can be short-circuited. But i'm guessing that's not belonging to this question – Lino Nov 02 '17 at 09:55