Which out of the following two equivalent ways would be best for the null conditional operator in terms of primarily performance and then ease of use or clarity etc.?
This:
idString = child?.Id;
fatherName = child?.Father?.Name;
motherName = child?.Mother?.Name;
or (assuming that all local vars are null already) this:
if (child != null)
{
idString = child.Id;
fatherName = child.Father?.Name;
motherName = child.Mother?.Name;
}
Is performance even an issue?
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:
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.