I am writing algorithms that work on series of numeric data, where sometimes, a value in the series needs to be null. However, because this application is performance critical,
One can avoid some of the performance degradation associated with Nullable
by defining your own structure
struct MaybeValid
{
public bool isValue;
public T Value;
}
If desired, one may define constructor, or a conversion operator from T
to MaybeValid
, etc. but overuse of such things may yield sub-optimal performance. Exposed-field structs can be efficient if one avoids unnecessary data copying. Some people may frown upon the notion of exposed fields, but they can be massively more efficient that properties. If a function that will return a T
would need to have a variable of type T
to hold its return value, using a MaybeValid
simply increases by 4 the size of thing to be returned. By contrast, using a Nullable
would require that the function first compute the Foo
and then pass a copy of it to the constructor for the Nullable
. Further, returning a Nullable
will require that any code that wants to use the returned value must make at least one extra copy to a storage location (variable or temporary) of type Foo
before it can do anything useful with it. By contrast, code can use the Value
field of a variable of type Foo
about as efficiently as any other variable.