Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

' ... != 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 :) )

like image 794
asela38 Avatar asked Mar 08 '10 00:03

asela38


People also ask

Does .equals work on null?

equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null .

Can I compare null with null in Java?

We can simply compare the string with Null using == relational operator. Print true if the above condition is true.

How do you compare null values in if condition?

Use an "if" statement to create a condition for the null. You can use the boolean value as a condition for what the statement does next. For example, if the value is null, then print text "object is null". If "==" does not find the variable to be null, then it will skip the condition or can take a different path.

How do you check if an object is null?

Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .


1 Answers

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.

like image 142
polygenelubricants Avatar answered Oct 11 '22 08:10

polygenelubricants