4 comments on “Null coalesce vs If null check

  1. As I told you, seeing this makes me think of a little mistake.

    Actually if look at the IL of the Null Coalesce Operator it says
    brtrue.s IL000b

    Where IL000b says stloc.0

    that means when duplicate (dup) value of the same object is compared with stloc.0 (original object) and comparison evaluates to true, assign stloc.0.

    Otherwise it will get ldnull.

    This dup is expensive and creates replica of your original object for comparison and stores in evaluation stack.

    That means it will say the Runtime to check with null if it is true with first operand and then otherwise assign something ( in ur case it is null).

    Same is when you do like

    if(obj == null)
    result = obj;

    But if stores the result of the equality into a variable. In your IL you can see ldc.i4.0 which indicates that it pushes integer equivalent of the equality in stack stloc.1(first location). This is because if can have multiple else .. and if you dont store it to a storage, it would be difficult to handle the IL with jumps.

    Hence both of them are pretty much equal.

    BTW, you missed out the assignment operation in your example that makes if to be more faster than the other.

  2. Nope abhi, i did try both cases as well. And seem to get the similar output results. Hence i didn’t post it.

    But besides this, i don’t understand how they are almost equal when the performance figures are varying?

  3. Well, I have tried your sample with additional assignment in If and saw this output
    http://twitpic.com/6tmg8k

    Actually they are almost same but not exactly. As you can see the performance figures is slightly different, with Null Coalesce operation is slightly higher than If. This is because of dup statement in null coalesce operator.

    What do you think ?

  4. I have edited my post again to answer you. And its strange you getting a closer difference than mine. But hey is it because i am doing all this on a Win 7 under Virtual box running on Linux? I have configured virtual box to provide only 1 core of my processor to win 7 or virtual box.

    Oh well, i have dedicated win 7 here. I rarely use it though. Any ways i shall boot in there and check it again sir. Thanks :)

    UPDATE: I checked on dedicated win 7 here. With less number of iterations viz 100, 200 i seem to get very close difference which we can easily rule out. But upon increasing to 1000 or double of it, there comes a bit of more difference.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s