Which has better performance: test != null or null != test

java, null

Solution

No difference.

Second one is merely because C/C++ where programmers always did assignment instead of comparing.

E.g.

// no compiler complaint at all for C/C++
// while in Java, this is illegal.
if(a = 2) {
}
// this is illegal in C/C++
// and thus become best practice, from C/C++ which is not applicable to Java at all.
if(2 = a) {
}

While java compiler will generate compilation error.

So I personally prefer first one because of readability, people tend to read from left to right, which read as `if test is not equal to null` instead of `null is not equal to test`.

Problem

Consider the following two lines of code ``` if (test ! = null) ``` and ``` if (null != test) ``` Is there is any difference in above two statements, performance wise? I have seen many people using the later and when questioned they say its a best practice with no solid reason.

Original source

Related problems