Can anyone tell me what the performance cost is of checking if an object or property of an object is null in c#? I am working on an ASP.NET MVC application that the null checking is being done in the Model and then done again in the view. I feel that this is excessive but if there is no real performance hit then I don't see the harm in doing things this way.
-
2What did your performance tools tell you when you tested? – Thom Smith Aug 28 '12 at 19:02
-
1Very, very, very small. Unless you've identified a null check as a performance bottleneck, don't worry about it. – jrummell Aug 28 '12 at 19:03
-
2Why not profile it and find out for yourself. It's easy enough to do with the Stopwatch class. – Sam Axe Aug 28 '12 at 19:03
-
For a web application, it should be confidently ignorable. – mostar Aug 28 '12 at 19:04
-
4The hit for handling an exception will cover a lot of `null` checks. – HABO Aug 28 '12 at 19:08
-
Thanks for all your responses. – Jeremy Aug 28 '12 at 20:14
-
Possible duplicate of [Check if null before set to null?](http://stackoverflow.com/questions/42416970/check-if-null-before-set-to-null) – TheLethalCoder Feb 23 '17 at 16:25
3 Answers
I don't think its measurable if you're doing it just once while rendering and once while initializing the model.
It would have an impact if it were inside a computation-intensive loop though.
Things like querying the database, read/write to files, etc. are the ones you should watch out for.

- 22,194
- 16
- 64
- 99
Almost insignificant. Doing this twice is not a problem. Doing it a bajillion times is probably still not a problem (but would be indicative of some other programming issue)

- 6,509
- 8
- 40
- 70
Well of course there is SOME performance hit, checking if something is null takes some instructions...
If you'd like to minimize performance hit, use the ILDASM tool to view the CIL code of the method you're using and examine the actual execution path that is taking place. I'd even say: make sure you're using something like Object.ReferenceEquals (as opposed to the instance's Equals method, or the equality operator).

- 8,044
- 33
- 51
-
2Do you have any articles or links explaining in more details how `Object.ReferenceEquals` is better than the others, This is quite an interesting topic. I generally just do: `id(myValue != null)` – Zapnologica Dec 17 '15 at 06:48