Say that a method has an optional Action or Func<T, T> argument that will usually be the default value of null. This usually-null lambda expression will be called many times.
In this situation, is it better to:
Null-check the lambda expression before each use, or...
a. Call nullable Action's using action?.Invoke().
b. Call nullable transform Func<T, T>'s as transform == null ? value : transform(value).
...null-check the expression once when the method is called, then replace it with a transparent variant?
a. Replace null Action's with new Action(() => { }).
b. Replace null Func<T, T>'s with new Func<T, T>((T value) => { return value; }).
For this question, please assume:
This is deeply nested math code, so its performance is relevant.
The code's readability is not meaningfully affected.
I ask this question because I frequently have methods that allow for optional lambda expressions, which are incredibly useful, but I'm never sure if I should null-check them on declaration or if I should just null-check them on each potential usage.
I imagine that, if the lambda expression will only be executed once, then it's best to just null-check at that point.
But, I'm curious about when the method constructs an object that will call the lambda expression many times. Assuming that the argument will usually be null, then it seems like this question reduces to a simpler question: is it faster to null-check a lambda or execute one that doesn't do anything?
If you check this answer you will see some performance benchmarks for a very similar delegate problem, although in this case it has to do with raising events:
The cost for raising an event with an empty delegate is roughly twice that for raising it with a null check first.
I'm imagining that performance implications would be similar for your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With