Java is not equal (! =) The difference in performance

I was always taught in my first job as a Java developer to avoid using "! =", But instead use an empty if clause, then put the logic in else:

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

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

Our leading developers reasoned about avoiding an unnecessary bit switch, especially for simple logic, for example, to check for zero.

I have searched for sources that talk about this, but I cannot find them. Is the procedure โ€œemptyโ€ if the proposal is really โ€œbest practiceโ€ or just preference?

+4
source share
1 answer

IMO, this is an unsuccessful attempt at micro-optimization.

Compile 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

  }

. . IMO, .

x null, blah, - .

+10

Source: https://habr.com/ru/post/1538506/


All Articles