简体   繁体   中英

the advantage of nullable variable in memory allocation C#

I had read some article explain about nullable<T> type variable, so far I not found any article explain the effect of nullable<T> type variable compare with non-nullable type variable.

is that nullable<T> type variable will consume lesser memory allocation? or both of them is same

add-on

so we are not necessary to use nullable<T> for every variable when it have no possibility to be null?

Assuming you are talking about the Nullable<T> type, then it will always use more memory than the equivalent non-nullable type.

Both are value types and so can be stored eg on the stack when used as parameters or local variables, or as individual elements within a contiguous block of memory (ie as an array), which can in some situations improve memory usage characteristics. In other words, with Nullable<T> you get some reference type semantics, without some of the storage-related drawbacks.

But an instance of Nullable<T> necessarily contains both the nominal value (even when the effective value of the instance is null , the storage for the non-nullable type still exists), along with a flag indicating whether or not the instance should be treated as a null value. Obviously "value plus a flag" will take more memory than just "value".

Note that the implementation of Nullable<T> , at least from a storage perspective, looks like this:

public struct Nullable<T> where T : struct
{
    private bool hasValue; 
    internal T value;
}

You can clearly see the value and the flag here. The non-nullable equivalent for any variable of type T would of course have only the value. The extra bool represents an additional memory requirement.

Thus, for any value type T , an instance of Nullable<T> will take up more memory than an instance of T .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM