Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(a != null) or (null != a)

Is there any difference in comparing a variable with null or comparing the null with a variable?

For example, which comparation is better (a != null) or (null != a) ? I've read somewhere that the second one is faster but didn't find the reason for this.

like image 738
Ramona Avatar asked Dec 21 '11 09:12

Ramona


1 Answers

No, none is faster. That's a plain lie. There is no advantage of using the second version. Only making readability worse.

This all came from C, where you could erroneously write

if(x = 3) 

instead of

if( x == 3)

Some people thought that it'd be best to write the constant first, in which case if you wrote =instead of ==, you'd get a compiler error. So some sources recommended writing

if(3 == x)

Some people didn't know why this was necessary and carried on and generalized this idea to constructs and languages where it makes absolutely no sense. IMO it didn't make a lot of sense in the original C context either, but that's a matter of personal taste.

like image 117
Armen Tsirunyan Avatar answered Oct 01 '22 02:10

Armen Tsirunyan