简体   繁体   English

内存分配中可空变量的优点C#

[英]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. 我读过一些关于nullable<T>类型变量的文章解释,到目前为止我还没有发现任何文章解释了nullable<T>类型变量与非可空类型变量的比较。

is that nullable<T> type variable will consume lesser memory allocation? 可以为nullable<T>类型变量会消耗较少的内存分配吗? 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? 所以当没有可能为null时,我们没有必要为每个变量使用nullable<T>

Assuming you are talking about the Nullable<T> type, then it will always use more memory than the equivalent non-nullable type. 假设您正在讨论Nullable<T>类型,那么它将始终使用比等效非可空类型更多的内存。

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. 换句话说,使用Nullable<T>可以获得一些引用类型语义,而没有一些与存储相关的缺点。

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. 但是Nullable<T>的实例必然包含标称值(即使实例的有效值为null ,非可空类型的存储仍然存在),以及指示实例是否应该是的标志作为null值处理。 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: 请注意, Nullable<T>的实现(至少从存储角度来看)如下所示:

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. 类型T任何变量的非可空等价当然只有值。 The extra bool represents an additional memory requirement. 额外的bool表示额外的内存要求。

Thus, for any value type T , an instance of Nullable<T> will take up more memory than an instance of T . 因此,对于任何值类型TNullable<T>的实例将占用比T的实例更多的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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