Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come NullReferenceException is more expensive than any other exception in CLR?

While looking for null check vs catching NullReferenceException, I came across this.

Catching a null dereference is one of the most expensive operations that the CLR can perform, and this could have a severe performance impact if your code is throwing a lot of NullReferenceExceptions. Testing for nullity and doing something else about it (even throwing an exception!) is a cheaper operation.

Here is a link of the question where I found it. When is handling a null pointer/reference exception preferred over doing a null check?

I am wondering how can catching NullReferenceException be more expensive than null check and throwing exception.

[couldn't comment there because of insufficient reputation numbers]

like image 356
finch Avatar asked Sep 22 '16 05:09

finch


1 Answers

The point here is not that a NullReferenceException is more expensive than any other exception. The cost of throwing exceptions comes from unrolling the stack and that depends more on the call structure than the specific exception. I believe the point the doc is trying to make is that it is less expensive to safe-guard against the exception in the first place, than it is to handle it when its thrown.

like image 179
Brian Rasmussen Avatar answered Sep 19 '22 02:09

Brian Rasmussen