tags:

views:

443

answers:

4

Is it true that the smallest amount of memory that I can allocate in managed code is a byte?

Do I understand correctly that a Boolean variable takes up much more than a bit of memory?

Is there a way for me to allocate memory, in .net, in chunks smaller than a byte?

+8  A: 

This is correct, allocations are made on a granularity of byte (possibly rounded up to an even number of bytes or even higher). This is true of any OS I've worked with, so it's not specific to managed code. The memory manager works with bytes, not bits.

On the other hand, it's not hard to pack booleans into a bit array if you have lots of booleans and want to achieve higher storage efficiency (see BitArray).

Liedman
+5  A: 

You cannot allocate memory on any computer - that I'm aware of - in amounts smaller than one byte, definetly not on a PC.

Also, with .net you aren't allocating any memory, thats all looked after for you unless you're using C++ in .Net (with garbage collection it's possibly better to say you're "using" memory rather than "allocating" memory, it's practically impossible to tell if a call to new will allocate memory or reuse memory).

If you are using C++, even though you might ask for one byte, the Operating System will allocate a block of memory for your program to use, which will almost certinaly be more than one byte.

If you want to store an array of bits you can roll your own BitArray collection, where the minimum you'll store is a byte (actually you should use ints) and you pack and unpack the bits into and out of that.

Luckly .Net 3.5 comes with a BitArray class (as apparently did 1.0, 1.1, 2.0, 3.0 . . . thanks Joe)

However, there is always a cost. Packing and unpacking bits will be slower than keeping an array of booleans.

Hope this helps

Binary Worrier
> Luckly .Net 3.5 comes with a BitArray class. The BitArray class has been around since 1.0 AFAIK.
Joe
+2  A: 

If you have lots of booleans that you want to store in a space-efficient way, take a look at the BitArray class.

Arnout
A: 

Try migrating to a Intel 4040. Then your booleans will only use 4-bits. However if you don't find one in the flea market, or happen to have on in the attic, I'd recommend bit-arrays, because with the incredible advent of 64-bit, your booleans will become as big as Doubles, the horror!

Robert Gould
Not (necessarily) true. Allocating an array of bool will take on byte per bool, either if you're running on 64 bit or 32. Its a common misconception that everything will have to be 64 bit just because it's a 64 bit OS; it just means you CAN shuffle 64 bits atomically if you want it.
Liedman
not talking about arrays, anyways I guess you failed to see the REAL point of the answer...
Robert Gould