pattern check null first! #8251
-
many of the syntaxes shown at Pattern matching overview the docs should also advise perf improvement to sequence individual tests s.t. number of comparisons is minimised [subject to logic], i.e. normally consider the frequent path before the rare unless those rare outliers can be checked first so remaining frequent cases can be handled by the discard catch-all. BTW I originally post this on VS/C# repo Pattern matching overview but Jared Parsons recommended re-posting here instead. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Let me see if I'm understanding your point correctly; for this example, you're suggesting to move the public decimal CalculateDiscount(Order order) =>
order switch
{
{ Items: > 10, Cost: > 1000.00m } => 0.10m,
{ Items: > 5, Cost: > 500.00m } => 0.05m,
{ Cost: > 250.00m } => 0.02m,
null => throw new ArgumentNullException(nameof(order), "Can't calculate discount on null order"),
var someObject => 0m,
}; If that's the case, then I have good news for you: you don't have to reorder anything here. Switch statements and expressions already handle this. The underlying logic is somewhat complicated (involving topological graph sorting), but the gist of it is: if it's possible to avoid checking something twice, we won't check it twice. A property pattern, like |
Beta Was this translation helpful? Give feedback.
-
I think it should very well be left to the C# compiler to produce optimal code for patterns by reordering null checks that would happen implicitly anyway (like in property patterns). The developer should be able to focus on readability, maintainability and the requirements of the domain and not have to think about these things. |
Beta Was this translation helpful? Give feedback.
-
one more explained/documented/fixed; thanks Team ! |
Beta Was this translation helpful? Give feedback.
Let me see if I'm understanding your point correctly; for this example, you're suggesting to move the
null
branch first?If that's the case, then I have good news for you: you don't have to reorder anything here. Switch statements and expressions already handle this. The underlying logic is somewhat complicated (involving topological graph …