Skip to main content

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?

Comments

Popular posts from this blog

Architecture Complexity

Here are the items to consider: Coding to an interface Service Oriented Architecture Automated Testing Domain Driven Design Custom Data Access Layer Layered architecture Complexity is relatively equal the number of lines of code. Note that complexity is not bad. It must be justified.

Android Studio:Unknown Host Error

After installing Android Studio, I got the following error: Unknown host 'services.gradle.org'. Please ensure the host name is correct. If you are behind an HTTP proxy, please configure the proxy settings either in Android Studio or Gradle. Consult IDE log for more details (Help | Show Log) Solution File --> Settings --> HTTP Proxy --> Auto-detect proxy settings

Brain as the tool of the spirit

The mind as the bridge between pure consciousness and the body in which that consciousness temporarily resides.