Cost of null references during runtime

Are null reference exceptions expensive during runtime (do they cause lag)? I assume that these are handled by Unity, thus the nice debug message, but I was wondering if I should bother checking that certain references are not null before trying to carry out some action with them in order to improve performance, or would that be a waste of time?

For example, if I’m getting a component from a RayCastHit, should I bother checking that the hit is on a certain object that I know has the component, or should I even bother?

I know its as simple as adding something like

if (someObject.GetComponent<someComponent>() != null){

but should I even bother, or just let Unity handle it?

There is no concern to have on null checks, there are micro optimisation that will not affect your app in the end.

On the other hand, this could:

someComponent comp = someObject.GetComponent<someComponent>();
if (comp != null){

in your case you are running GetComponent to check if the component is there and then you call it again to perform the action. In my case, I call once and do both actions.

Your game does not crash in Editor because Unity prints the debug and keeps going with some workaround, but if you run on device, it will most likely crash or freeze.

The short answer is “You HAVE to avoid null references”.

JetBrain’s Ride warns using the null checks in ‘performance critical context’