Which is more effective: if (null == variable) or if (variable == null)? [duplicate]
In Java, which will be more effective, and what are the differences?
if (null == variable)
or
if (variable == null)
Solution 1:
(Similar to this question: Difference between null==object and object==null)
I would say that there is absolutely no difference in performance between those two expressions.
Interestingly enough however, the compiled bytecode (as emitted by OpenJDKs javac) looks a bit different for the two cases.
For boolean b = variable == null
:
3: aload_1 // load variable
4: ifnonnull 11 // check if it's null
7: iconst_1 // push 1
8: goto 12
11: iconst_0 // push 0
12: istore_2 // store
For boolean b = null == variable
:
3: aconst_null // push null
4: aload_1 // load variable
5: if_acmpne 12 // check if equal
8: iconst_1 // push 1
9: goto 13
12: iconst_0 // push 0
13: istore_2 // store
As @Bozho says, variable == null
is the most common, default and preferred style.
For certain situations however, I tend to put the null
in front. For instance in the following case:
String line;
while (null != (line = reader.readLine()))
process(line);
Solution 2:
That's called "Yoda Conditions" and the purpose is to prevent you from accidentally using assignment (=
) instead of equality checking (==
).