In this article, i shall talk about internals of null checking on a type (ref type mostly) by using null coalesce operator or via if condition.
Null coalesce operator in c# is ?? and you can use it as shown below:
Now, lets us dig into the internals of IL , if IL is generated for the below code:
The IL is as shown:
As you can see from the above IL code, line 17-23 is the code for Null coalesce operator and from line 25 – 30 is for if condition. As you can see IL instructions generated by compiler is almost same in number viz. ~6 opcodes for both conditional statements. So logically it looks like both doesn’t have any run time performance benefits for us.
So one might wonder, which one to use? I would say you can’t have else part condition for a null coalesce operate. So in this case, you cant use null coalesce condition checking.
But before concluding, lets also do some run time performance analysis on them. For that, i have written this following test code:
(click on image for better view)
As per the above test code with 1000 iterations, this is the result i got:
As you can see from the multiple output samples, it shows that the first sample output is taking more time. I am guessing this is because many objects have to be created for the first time since the application loads up. So its better to discard that sample. But as per the rest 4 samples is concerned it shows that the performance output (all values are in Ticks) for null coalesce is a bit more than if condition one.
Now lets reduce the iteration to 100 each and see, how it behaves. Below is the output:
Again as you can see, the difference is more now. Although i ran for multiple times and got the similar performance output in both the cases.
So now we can say that its better to use if condition to check for null for an object even though we get a small gain in performance.
Thanks & Happy coding :)
- Upon changing the ref type i.e string in above code to a nullable int, i seem to get the similar output. Hence performance is not influenced by the types here.
- Also based on suggestion i re-tested by adding “result = null” in the if condition body under second for loop in the above code. So after doing so here is the output samples i got: