hi expert, want to ask, in java if(NULL==variables) or if(variables==NULL) which will be more effective and what are the difference,
thanks
hi expert, want to ask, in java if(NULL==variables) or if(variables==NULL) which will be more effective and what are the difference,
thanks
I would say that there is absolutely no difference in performance between those two expressions.
Interestingly enough however, the compiled bytecode (as emitted by Suns 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);
No difference.
if (variable == null)
is (imo) a better programming style.
Note that null
is lowercase in Java.
no difference
(null == variables)
was sometimes used in good old times (C language)
to avoid writing:
(variable = NULL)
by mistake
The first is a hang over from C where it is perfectly legal to write if(variable = NULL)
That's called "Yoda Conditions" and the purpose is to prevent you from accidentally using assignment (=
) instead of equality checking (==
).
Short answer: no difference.
Longer answer: there is stylistic difference which is rather subjective. Some people argue constants should be in the left as a defensive style just in case you mistyped ==
into =
. Some people argue constants should be in the right because it's more natural and readable.
A well designed language combined with a good compiler and static analysis tools, paranoia can be minimized, so you should write the most readable and natural code, which would be the constant on the right.
Please use the search function next time.
My opinion: Don't care about such insignificant performance optimizations. If you have bad performance, find and target the real problems/bottlenecks in your code.