我写了两个方法来检查它们的性能。
public class Test1 {
private String value;
public void notNull(){
if( value != null) {
//do something
}
}
public void nullNot(){
if( null != value) {
//do something
}
}
}
我检查了它编译后的字节码
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 */
}
这里使用了两个操作码来实现if条件语句:第一种情况使用ifnull——检查堆栈顶部的值是否为null-,第二种情况使用if_acmpeq——检查堆栈中的前两个值是否相等。
所以,这会对性能产生影响吗? (这将帮助我证明第一种空值实现在性能和可读性方面都很好 :))