Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which has better performance: test != null or null != test [duplicate]

Tags:

java

null

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.

like image 669
Sandeep Nair Avatar asked May 08 '12 07:05

Sandeep Nair


2 Answers

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.

like image 106
Pau Kiat Wee Avatar answered Nov 14 '22 20:11

Pau Kiat Wee


They are exactly the same. The second one can make sense when using equals:

if("bla".equals(test))

can never throw a NullPointerException whereas:

if(test.equals("bla")) 

can.

like image 30
assylias Avatar answered Nov 14 '22 22:11

assylias