Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
3.54/5 (4 votes)
See more:
Hi,
Question is regarding 2 different ways of null checking been done in C#

1: if(object == null)

2: if(null == object)

few says there are performance improvements when we use 2: like it will be easy for the compiler to convert the code. But i am not sure whether this information is correct. I normally prefer 1:

Is there any good reason to use 2:??

Regards

What I have tried:

Tried both the ways and found both works fine for me
Posted
Updated 23-Apr-17 9:06am
v2
Comments
Ralf Meier 19-Apr-17 6:25am    
I also prefer Version 1 - because my code everytime is written like "Variable" and "to compare with".
code4Better 19-Apr-17 6:29am    
But is there any difference between them..any idea?
Richard MacCutchan 19-Apr-17 6:38am    
There is no difference since the object code will be the same, compare a variable to a constant. The second example used to be recommended to avoid errors such as
if (object = null)
but most, if not all, compilers will warn you of the possible side effects of such a statement.
Rob Philpott 24-Apr-17 7:05am    
You, sir, are a lone voice of reason on this question. I can't believe what I'm reading below and what qualifies as 'proof'.
Richard MacCutchan 24-Apr-17 7:08am    
Well that's a first for me. :)

There will be no difference in the generated code. It is a comparison between a variable and a constant value. When the code is finally converted to assembly instructions, it will (depending on the CPU architecture) load the variable into a register and compare with the fixed value (or in this special case where the constant value is zero check the register for being zero), or compare a memory location with a constant value.

[EDIT2]
I was too related to C/C++ and forgot that conditions must evaluate to a bool.
[/EDIT2]
But the second form has an advantage if you type only one equal sign by mistake:
C#
// Assigns null to object, condition is always false
if (object = null)
{
}
// Compiler error
if (null = object)
{
}

[EDIT]
Using an object and null is not the best example here.

It makes more sense for integral types like int:
C#
if (0 = num)

However, this should also generate a warning about a condition that is always false.
[/EDIT]
 
Share this answer
 
v5
Comments
Richard MacCutchan 19-Apr-17 6:35am    
The first example raises a warning in VS.
[no name] 19-Apr-17 6:52am    
I think it would end in an error for c# "cannot implicitly convert tyoe 'object' to 'bool'
Richard MacCutchan 19-Apr-17 6:56am    
Exactly so.
code4Better 19-Apr-17 6:59am    
Yes you are correct. It will say cannot implicitly convert type object to bool.
F-ES Sitecore 19-Apr-17 7:46am    
Yes, it's something you'll only see in old code, it was a coding habit people used to try and get into in case they had a code typo when comparing\assigning. It's not prevalent these days as modern compilers and IDEs are so fast and powerful that the issue will be picked up quite quick. Back in those days however it would take 10 minutes to compile a large application so anything you could do to flag errors at compile time was a good thing.
It is my understanding that the second one does have a slight performance improvement. Something about only having to see if the second object is null or not rather than the first way it has to load the actual object and then compare against null.

I do not know the technical explanation real well but I had also learned once that it is slightly faster. I rarely write it that way because it does not read as well to me so it just depends on if saving a few microseconds is important to you or not.
 
Share this answer
 
Quote:
few says there are performance improvements when we use 2

Yes here is the proof
randomly ran the following code for 5 times and the results as below


obj == null
object obj = null;
     System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
     watch.Start();
     if (obj == null) { }
     watch.Stop();
     var a = watch.Elapsed.Ticks;

null == obj1
object obj1 = null;
            System.Diagnostics.Stopwatch watch1 = new System.Diagnostics.Stopwatch();
            watch1.Start();
            if (null == obj1) { }
            watch1.Stop();
            var b = watch1.Elapsed.Ticks;


Result
Elapsed Ticks
obj == nullnull == obj1
370
322
270
13518
379
 
Share this answer
 
v2
Comments
[no name] 19-Apr-17 11:19am    
A 5 for the effort(I hope you ran it enough times). Is this maybe also recognizable in the IL code?
Karthik_Mahalingam 19-Apr-17 23:12pm    
Thank you 0x01AA
ZurdoDev 19-Apr-17 14:01pm    
+5
Karthik_Mahalingam 19-Apr-17 23:12pm    
Thank you RyanDev
Ralf Meier 23-Apr-17 15:08pm    
I'm sorry ... I don't agree with you (this time).
Please take a look to my Solution (4)
Basicly I agree with Richard and Jochen.
Because of the results of Karthik I made my own test because I couldn't believe those results.

I tested it with VB.Net and also with C#.Net with this Code-Blocks :
VB
Dim myObject As Object = Nothing
Dim x As Boolean

Dim d1 As Date = Now

For i As Integer = 1 To 100000000
    If (myObject Is Nothing) Then x = True
Next

Dim d2 As Date = Now

For i As Integer = 1 To 100000000
    If (Nothing Is myObject) Then x = True
Next

Dim d3 As Date = Now

Dim ts1 As TimeSpan = d2 - d1
Dim ts2 As TimeSpan = d3 - d2


C#
object myObject = null ;
bool x = false;

System.DateTime d1 = System.DateTime.Now;

for (int i = 1; i <= 100000000; i++)
{
    if ((myObject == null))
        x = true;
}

System.DateTime d2 = System.DateTime.Now;

for (int i = 1; i <= 100000000; i++)
{
    if ((null == myObject))
        x = true;
}

System.DateTime d3 = System.DateTime.Now;

TimeSpan ts1 = d2 - d1;
TimeSpan ts2 = d3 - d2;


These are my results (by doing the compare 100 Million times :

Compare Timespan with VB Timespan with C#
myObj (assigned) to Nothing / Null 0,2390137 seconds 0,2808005 seconds
Nothing / Null to myObj (assigned) 0,3090174 seconds 0,2808006 seconds
myObj (not assigned) to Nothing / Null 0,3588006 seconds 0,3900007 seconds
Nothing / Null to myObj (not assigned) 0,2962005 seconds 0,2744006 seconds

Int-Constant to Integer-Variable 0,2652005 seconds 0,2652005 seconds
Int-Variable to Integer-Constant 0,2652005 seconds 0,2652005 seconds

I think that an average over 100 Million cycles says much more that an only 1 cycle-test (sorry Karthik) which shows different values with a big range.
But for me it was also very interesting that there is a difference (by handling Objects) between VB and C# ...
 
Share this answer
 
Comments
Karthik_Mahalingam 24-Apr-17 6:33am    
i have ran the same code
still there is difference of 100+ mill seconds

try this code
  object myObject = null;


        System.Diagnostics.Stopwatch watch1 = new System.Diagnostics.Stopwatch();
        watch1.Start();


        for (int i = 1; i <= 100000000; i++)
        {
            if (null == myObject) { }

        }
        watch1.Stop();


        System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
        watch.Start();

        for (int i = 1; i <= 100000000; i++)
        {
            if (myObject == null){}
               
        }
        watch.Stop();

      
        var a = watch.Elapsed.TotalMilliseconds;
        var b = watch1.Elapsed.TotalMilliseconds;
Ralf Meier 24-Apr-17 8:31am    
(maybe) my PC is not the fastes one ... :(
But for me it was important to see the percentual dependancy ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900