Why is a boolean 4 bytes in .NET?

前端 未结 6 2243
我在风中等你
我在风中等你 2020-11-29 07:54

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.

6条回答
  •  眼角桃花
    2020-11-29 08:24

    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 (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 Nullables takes only 2 bytes per object instead of 4 or 8.

    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.

提交回复
热议问题