Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a boolean 4 bytes in .NET?

Tags:

.net

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.

like image 645
Sun Avatar asked Nov 17 '08 04:11

Sun


People also ask

Why does a Boolean take a byte?

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.

How many bytes does a Boolean use?

Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False.

Why is a Boolean 8 bytes?

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.


1 Answers

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.

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.

like image 156
P Daddy Avatar answered Sep 27 '22 20:09

P Daddy