More efficient? No, I don't recall ever hearing that one.
Putting equality comparisons back-to-front is something that is usually done to avoid accidentally doing an assignment, by mis-typing "=" where you meant "==". By putting the constant (e.g. null) first, you make this mis-typing cause a compilation error, which is good, because it alerts you earlier to your mistake. It is more important in C and C++ than Java, because the mis-typed expression is more likely to be legal in C/C++ than in Java.
Having decided to do equality tests back-to-front, some people decide to do all tests back-to-front, for consistency. Dunno if I agree with that. [ October 20, 2005: Message edited by: Peter Chase ]
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Color me surprised - it actually does make a difference! Of course, the difference appears to be the opposite of what its proponents claim...
If you compile the following code:and then run javap -c on it, you get the following output:Note that putting null first takes a whole extra bytecode. Whether if_acmpne is faster than ifnonnull is a) likely to be dependent on the JVM, and b) even more likely to HotSpotted into invisibility.
Personally, I find putting the null first to be disconcerting - the "WTF Factor" mentioned above. So I don't do it that way. And I use Lint in C, to point out errors like doing assignments in if-clauses, which is the original reason for the convention.
In Theory, there is no difference between theory and practice.<br />In Practice, there is no relationship between theory and practice.
As Grant mentions, this practice comes from C and C++ because you can do something like
if (var = NULL)
when you really mean
if (var == NULL)
but the compiler won't catch it. This is because the result of an assignment (i.e. the = operator) is the value of the right hand operand. Also, the if statement can take any type of expression. The condition is false if it evaluates to 0 and true otherwise. In this case, the above if statement always evaluates to false. To avoid this, some people use
if (NULL == var)
because if you accidentally type
if (NULL = var)
it will cause a compiler error.
I think this convention is just a hold-over from C++ and has no significant performance ramifications in Java.