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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With