asela38 asela38 - 8 days ago 5
Java Question

' ... != null' or 'null != ....' best performance?

I wrote two methods to check there performance

public class Test1 {

private String value;

public void notNull(){
if( value != null) {
//do something
}
}

public void nullNot(){
if( null != value) {
//do something
}
}

}


and checked it's byte code after compiling

public void notNull();
Code:
Stack=1, Locals=1, Args_size=1
0: aload_0
1: getfield #2; //Field value:Ljava/lang/String;
4: ifnull 7
7: return
LineNumberTable:
line 6: 0
line 9: 7

StackMapTable: number_of_entries = 1
frame_type = 7 /* same */


public void nullNot();
Code:
Stack=2, Locals=1, Args_size=1
0: aconst_null
1: aload_0
2: getfield #2; //Field value:Ljava/lang/String;
5: if_acmpeq 8
8: return
LineNumberTable:
line 12: 0
line 15: 8

StackMapTable: number_of_entries = 1
frame_type = 8 /* same */


}


in here two opcodes are used to implement the if condition: in first case it use ifnull- check top value of stack is null-, and in second case it use if_acmpeq- check top two value are equal in the stack-

so, will this make an effect on performance?
(this will helps me to prove first implementation of null is good in performance wise as well as in the aspect of readability :) )

Answer

Comparing the generated bytecodes is mostly meaningless, since most of the optimization happens in run time with the JIT compiler. I'm going to guess that in this case, either expression is equally fast. If there's any difference, it's negligible.

This is not something that you need to worry about. Look for big picture optimizations.