Why BitVector 32 structure is more efficient than BitArray?

Jaywith.7 picture Jaywith.7 · May 24, 2009 · Viewed 16.5k times · Source

What is the difference between BitArray and BitVector 32 structure and what are the advantages of BitVector 32 structure over BitArray? Why is the BitVector 32 structure more efficient than BitArray?

Thanks in advance.

Jay...

Answer

Matt Brindley picture Matt Brindley · May 24, 2009

BitVector32 is more efficient than BitArray for Boolean values and small integers that are used internally. A BitArray can grow indefinitely as needed, but it has the memory and performance overhead that a class instance requires. In contrast, a BitVector32 uses only 32 bits.

http://msdn.microsoft.com/en-us/library/system.collections.specialized.bitvector32.aspx

BitVector32 is a struct and consumes only 4 bytes. BitArray is a class that has overheads associated with it and is therefore less efficient - BitArray will need at least 8 bytes before you've even added any objects to it as it lives on the heap. More about the stack and heap here.