Monday, June 07, 2010

Performance of null checks in Java

Which one is faster? a == null or null == a?


This is the method of the former.



public static boolean firstNullCheck(Object a) {
if (a == null) {
return true;
}
return false;
}

and the method of the latter.



public static boolean secondNullCheck(Object a) {
if (null == a) {
return true;
}
return false;
}

Here’s the disassembly of the former.



public static boolean firstNullCheck(java.lang.Object);
Code:
0: aload_0
1: ifnonnull 6
4: iconst_1
5: ireturn
6: iconst_0
7: ireturn

and the disassembly of the latter.



public static boolean secondNullCheck(java.lang.Object);
Code:
0: aconst_null
1: aload_0
2: if_acmpne 7
5: iconst_1
6: ireturn
7: iconst_0
8: ireturn

The former saves you a bytecode. Anyone who can explain further since I am not sure whether if_acmpne is faster than ifnonnull?

No comments: