tags:

views:

1443

answers:

7

Why System.Boolean takes 4 bytes even if it just stores one state TRUE or FALSE; which may be stored less than 4 bytes?

+6  A: 

The first result on a Google search for System.Boolean size told me that it's to do with memory alignment. It's faster to push around a four-byte Int32 than it is to work with individual bytes/bits.

Matt Hamilton
Nice touch with the URL :)
Tom
+5  A: 

Because it's fast.

A 32-bit processor typically works with 32-bit values. Working with smaller values involves longer instructions, or extra logic.

Artelius
+2  A: 

I think it's only for performance, 32 bit values are much more efficient to manipulate.

CMS
A: 

Where'd you get that? System.Boolean takes only 1 byte.

Just try:

Console.WriteLine( sizeof( System.Boolean ).ToString() );
arul
Check the size after the type has been marshaled: Console.Write(System.Runtime.InteropServices.Marshal.SizeOf(new System.Boolean()));
CMS
Which is what you shouldn't do. Most of the unmanaged API's use *int* for BOOL values, Marhsal.SizeOf() tells you size of an *unmanaged* type.
arul
Marshalling a bool is slighly more complicated than that. I did a blog post on this subject which covers the various sizes: http://blogs.msdn.com/jaredpar/archive/2008/10/14/pinvoke-and-bool-or-should-i-say-bool.aspx
JaredPar
+14  A: 

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.

P Daddy
Even Nullable<bool> will only use up two bytes in some cases - for instance if you've got an array of them.
Jon Skeet
Yes, you're right. I would have expected it to align array indices for performance's sake, but it doesn't seem to.
P Daddy
+1  A: 

Duplicated here.

Gorpik
A: 

sorry

it prints 4 byte:) bool b=false; Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(b).ToString());

also I don`t understand that...

// char type prints 2 byte

Console.WriteLine( sizeof( System.char ).ToString() );

// prints 1 byte

char c='@'; Console.WriteLine( sizeof( c ).ToString() );