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 :) )
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 .
We can simply compare the string with Null using == relational operator. Print true if the above condition is true.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With