为什么在.NET中布尔值为4个字节? [英] Why is a boolean 4 bytes in .NET?

查看:132
本文介绍了为什么在.NET中布尔值为4个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么System.Boolean占用4个字节?它只存储一个状态,即 true false ,可以将其存储在小于4个字节的空间中。

Why does a System.Boolean take 4 bytes? It just stores one state, either true or false, which could be stored in less space than 4 bytes.

推荐答案

bool 实际上只有1个字节,但是对齐可能导致4个字节在32位平台上使用,甚至在64位平台上为8个字节。例如, Nullable< bool> (又名 bool?)类型使用完整的32位或64位,具体取决于平台-即使仅由两个 bool 组成。 编辑:正如乔恩·斯凯特(Jon Skeet)指出的那样,总是不存在用于对齐的填充。例如, Nullable< bool> s的数组每个对象仅占用2个字节,而不是4或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 bools. 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位也被认为是浪费。因此,如果创建的类型具有很多 bool 作为成员,(或使用很多 Nullable<> 类型),类的用户可能会创建它的许多实例,您可以考虑使用 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 bools 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中布尔值为4个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆