Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does boolean consume more memory than char?

Why does a Boolean consume 4 bytes and a char 2 bytes in the .NET framework? A Boolean should take up 1bit or at least be smaller than a char.

like image 815
Razor Avatar asked Oct 15 '08 10:10

Razor


People also ask

Is Boolean smaller than char?

However, my C++ book (C++ Pocket Reference, O'Reilly) states: "The typical size of a bool is one byte," and "The size of a char is one byte. The size of a byte technically is implementation defined, but it is rarely anything but eight bits."

How much memory a Boolean variable takes and why?

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.

Why is a Boolean 4 bytes?

Because it's fast. A 32-bit processor typically works with 32-bit values. Working with smaller values involves longer instructions, or extra logic.


1 Answers

It is a question of memory alignment. 4-byte variables work faster than 2-byte ones. This is the reason why you should use int instead of byte or short for counters and the like.

You should use 2-byte variables only when memory is a bigger concern than speed. And this is the reason why char (which is Unicode in .NET) takes two bytes instead of four.

like image 134
Gorpik Avatar answered Oct 11 '22 04:10

Gorpik