Is performance even a problem?
Short answer: Performance about null checks will never be a problem in a regular application. It is only a matter of readability and maintainability.
Performance:
Yes, you have 3 “explicit” checks against 1. But you should keep in mind that:
- The system performs an “implicit” check of the null value each time you refer to an object instance, as described here , and afaik JIT doesn Optimize null checks. So in your case, the bet is not 3 against 1.
- Zero checking is a very (very, very) cheap operation compared to most of the operations that you perform in a normal software stream (allocating a heap of instances, mathematical calculations, linq query, rendering a graphical object, parsing strings, ...).
I see only the remote possibility of significant differences in performance: if the child
or Mother
or Father
are not local variables or simple simple properties, but are methods and properties with very long runtimes. For example, the GetChild()
method, which GetChild()
2 seconds. Do you see a realistic scenario for this? I cant. Even so, you can call GetChild()
at a time and assign it to a local variable, and then call child?
3 times.
Resolution:
A single initial if
allows you to mentally separate different pieces of code. Pretend to be a code reader without knowing anything else: ask yourself if it’s easier to read “if the child is not null, all these operations and so on, otherwise just go” or “if the child is not null, check Name. If again the child is not null, check Mother. If Mother is not null, get the Mother’s Name. Then, if the child is not null again, check the Father. If the Father is not null .......... "
maintainability:
Aka, in this case, is the DRY principle . For example, why would you repeat the zero check 3 times? Imagine that at some point in the future your boss will ask you to change the code: you need not only to check the invalidity of the child, but also his Id
is 0 (such things happen very often in any software development process). In the first section of the code, you should fix 3 lines. In the second section of code, you should fix only one line: the initial if
.
And therefore, it is always better to centralize the algorithms and logical flows anywhere.
EDIT:
For a discussion of thread safety on the null conditional statement, see this question .