为什么.NET可选System.Boolean需要4个字节? [英] Why in .NET System.Boolean takes 4 byte?
问题描述
为什么可选System.Boolean需要4个字节,即使它只是存储一个状态TRUE或FALSE;其可以存储少于4字节?
Why System.Boolean takes 4 bytes even if it just stores one state TRUE or FALSE; which may be stored less than 4 bytes?
推荐答案
A 布尔
实际上只有1个字节,但调整可能会导致在32使用的4个字节比特平台,或者甚至8个字节在64位的平台上。例如,可空<布尔>
(?又名布尔
)的类型采用了全32位或64位,这取决于平台,即使它仅仅由两个布尔
取值。 修改:正如乔恩飞碟双向,填充对准不是的总是的present。举个例子,数组可空<布尔>
S可每个对象,而不是4只2个字节或8
A bool
is actually only 1 byte, but alignment may cause 4 bytes to be used on a 32-bit platform, or even 8 bytes on a 64-bit platform. For example, the Nullable<bool>
(aka bool?
) type uses a full 32 or 64 bits—depending on platform—even though it's comprised of just two bool
s. EDIT: As pointed out by Jon Skeet, padding for alignment isn't always present. As an example, an array of Nullable<bool>
s takes only 2 bytes per object instead of 4 or 8.
不过,即使8位,重新present一个布尔
可以被认为是一种浪费,如果你有很多人到店里。出于这个原因,如果你创建具有许多布尔
取值为成员(或使用许多类型可空&LT;&GT;
类型),和用户类可能会创建它的很多情况下,你可能会考虑使用 BitVector32
代替。该框架本身使用该技术,以减少许多的Windows的内存占用窗体控件,例如。
But even 8 bits to represent a bool
can be considered wasteful if you have many of them to store. For this reason, if you create a type that has many bool
s as members, (or uses many Nullable<>
types), and users of your class might create many instances of it, you might consider using a BitVector32
instead. The framework itself uses this technique to reduce the memory footprint of many of the Windows Forms controls, for instance.
这篇关于为什么.NET可选System.Boolean需要4个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!