Alternatives to nullable types in C#

后端 未结 6 1714
盖世英雄少女心
盖世英雄少女心 2021-02-07 15:44

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,

6条回答
  •  鱼传尺愫
    2021-02-07 16:14

    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.

提交回复
热议问题