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.
A bool takes in real 1 bit, as you need only 2 different values. However, when you do a sizeof(bool), it returns 1, meaning 1 byte. For practical reasons, the 7 bits remaining are stuffed. you can't store a variable of size less than 1 byte.
Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False.
A boolean type normally follows the smallest unit of addressable memory of the target machine (i.e. usually the 8bits byte). Access to memory is always in "chunks" (multiple of words, this is for efficiency at the hardware level, bus transactions): a boolean bit cannot be addressed "alone" in most CPU systems.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With