Is performance even an issue?
Short answer: Performance about null-checks will never be an issue in a normal application. It's only a matter of readability and maintainability.
Performance:
Yes, you have 3 "explicit" checks against 1. But you must keep in mind that:
- The system performs an "implicit" null-check every time you reference an object instance, as explained here, and afaik the JIT doesn't optimize null-checks at all. So in your case the rate is not just 3 against 1.
- A null-check is a very (really, very) cheap operation, compared with most operations you do in a normal software flow (instance heap allocation, mathematic calculations, a linq query, graphic object rendering, string parsing, ...).
I see only a remote possibility of significant performance differences: if child
or Mother
or Father
are not local variables or simple plain properties, but methods and properties with very long execution time. For example, a GetChild()
method that takes 2 sec to execute. Can you see a realistic scenario for that? I can't. Even if that's the case, you can call GetChild()
one single time and assign it to a local variable, then call child?
3 times.
Readability:
A single initial if
allows to mentally separate different chunks of code. Pretend to be the reader of the code, without knowing anything else: ask yourself if is it simpler to read "if child is not null do all this operations and stuffs, otherwise just move on", or "if child is not null check the Name. If again child is not null check the Mother. If the Mother is not null get the Mother's Name. Then if again child is not null check the Father. If Father is not null... ... ... ".
Maintainability:
Aka, in this case, the DRY principle. For example, why would you repeat the null-check 3 times? Pretend that at a certain point in the future your boss asks to you a code change: it is required not only to check the nullity of a child, but also if its Id
is 0 (things like that happen very frequently in any software development process). In your first code section you should correct 3 lines.
In your second code section you should correct only 1 line: the initial if
.
EDIT:
For a discussion about thread-safety on the null conditional operator, see this question.
child
is null, whereas the former code will assign null values to all variables in that case. Decide what behaviour you want first, then choose what you find most readable, then validate that performance meets your requirements. (If you haven't yet defined your performance requirements, that's the first thing to do...) – Vanover