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 usingaction?.Invoke()
.b. Call nullable transform
Func<T, T>
's astransform == 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 withnew Action(() => { })
.b. Replace
null
Func<T, T>
's withnew 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?