Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java not equal to (!=) performance difference

Tags:

java

I've always been taught in my first job as a Java Developer to avoid the use of "!=" but instead use an empty if clause then put the logic in the else:

//Bad:
if (x != null) {
   // logic
}

//Good:
if (x == null){
} else {
  // logic
}

Our lead developer's reasoning was to avoid an unnecessary bit-switch especially for simple logic like null checking.

I've been looking for sources that state this but I can't seem to find any. Is the empty if clause practice really a "best practice" or just a preference?

like image 841
Michael Sanchez Avatar asked Apr 29 '14 01:04

Michael Sanchez


1 Answers

IMO, this is a failed attempt at micro-optimisation.

Compile the code

public static void main(String... args) {
    Object x = null;
    //Bad:
    if (x != null) {
       // logic
    }

    //Good:
    if (x == null){
    } else {
      // logic
    }
}

and check with javap

  public static void main(java.lang.String...) 
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
    Code:
      stack=1, locals=2, args_size=1
         0: aconst_null
         1: astore_1
         2: aload_1
         3: ifnull        6
         6: aload_1
         7: ifnonnull     10
        10: return
      LineNumberTable:
        line 9: 0
        line 11: 2
        line 16: 6
        line 20: 10

  }

Both have a jump to another branch. There is no different in performance. IMO, the readability of your code suffers though.

If x is null, blah, otherwise logic.

like image 61
Sotirios Delimanolis Avatar answered Sep 23 '22 10:09

Sotirios Delimanolis