Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if(value == null) vs if(null == value) [duplicate]

Tags:

javascript

c#

php

Possible Duplicate:
Why does one often see “null != variable” instead of “variable != null” in C#?

This is more a curiosity question, is there any performance difference between the statement.

 if(value == null)

and

 if(null == value)

is it noticeable, I use c#, PHP & javascript quite often and I remember someone saying if(null == value) was faster, but is it really?

I will soon be starting development on an application that will parse huge quantities of data in the region of Terabytes so even if the performance gain is in the millisecond range it could have an impact. Anyone have any ideas?

like image 895
kamui Avatar asked Nov 08 '11 10:11

kamui


People also ask

What is the difference between null == object and object == NULL in Java?

There is absolutely no difference in either semantics or performance. The == in this case is a reference inequality operation; it can never throw NullPointerException .

Which is better null != object or object != Null?

Short answer: There is no difference, both are correct and do the same check. But, as @Ashish Mishra have answered, if you are using languages like C or C++, it's better to use if(null != object) just in case you forgot the "!" symbol.

How to check if a value is null or undefined in JavaScript?

The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator.

Is null checking C#?

NULL checks in C# v.The question mark symbol which used in if condition, which means that it'll check whether value is NULL, if not then it'll check whether Name is null. It'll check if the value is Null, if Null it'll return “value is null” string.


3 Answers

I doubt that there's a measurable performance advantage either way. I'll bet the person who told you this didn't have any hard data.

As far as I know, it's a historical artifact, a technique from C and C++ to guard against this mistake:

if (c = null) {
}

The compiler will catch this if you reverse the arguments, since you can't assign something to null.

like image 60
duffymo Avatar answered Sep 28 '22 07:09

duffymo


I profiled both over 100 million iterations.

if(value == null)
-- 6.85175704956 seconds (68.5 nano-seconds each)
if(null == value)
-- 6.75543808937 seconds (67.5 nano-seconds each)

So it's up to you if 1 nanosecond is enough of a gain.

like image 39
Niet the Dark Absol Avatar answered Sep 28 '22 09:09

Niet the Dark Absol


There is absolutely no performance difference to be expected.

The only reason the (ugly) form (if null == value) is used is to avoid a C/C++ specific typo:

if (value = null)  // compiles but _assigns_ null to value and always returns false
    ...  // never executed
like image 35
Henk Holterman Avatar answered Sep 28 '22 09:09

Henk Holterman