Double question marks ('??') vs if when assigning same var

Lockszmith picture Lockszmith · Jul 10, 2012 · Viewed 60.6k times · Source

Referring to the following SE answer.

When writing

A = A ?? B;

it is the same as

if( null != A )
    A = A;
else
    A = B;

Does that mean that

if( null == A ) A = B;

would be preferred, performance wise?

Or can I assume that the compiler optimizes the code when the same object is in the ?? notation?

Answer

Adam Houldsworth picture Adam Houldsworth · Jul 10, 2012

Don't worry about the performance, it will be negligible.

If you are curious about it, write some code to test the performance using Stopwatch and see. I suspect you'll need to do a few million iterations to start seeing differences though.

You can also never assume about the implementation of things, they are liable to change in future - invalidating your assumptions.

My assumption is the performance difference is likely very, very small. I'd go for the null coalescing operator for readability personally, it is nice and condense and conveys the point well enough. I sometimes do it for lazy-load checking:

_lazyItem = _lazyItem ?? new LazyItem();