Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why BitVector 32 structure is more efficient than BitArray?

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...

like image 836
Jaywith.7 Avatar asked May 24 '09 11:05

Jaywith.7


3 Answers

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.

like image 175
Matt Brindley Avatar answered Nov 13 '22 11:11

Matt Brindley


Here is what Microsoft's documentation for BitVector32 states:

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.

The capacity of BitVector32 is limited to 32 bits, the size of an int. Therefore, indexing and masking can be single operations. Compare this to a bit array with 734 bits and you want to find out if bit 197 is set. Think about how you would do that (from the perspective of the class designer).

like image 44
Sinan Ünür Avatar answered Nov 13 '22 12:11

Sinan Ünür


A BitVector32 gets it boost over BitArray because it is just a 32 bit integer and does not have the overhead associated with a class (mainly the memory overhead).

This means if you need to store more then 32 Boolean values then you will either need to use BitArray or multiple BitVector32. Since multiple BitVector32 might be cumbersum you might want to put them into an array or a class, which would remove the performance boost.

In short, if you need to store 32 or less Boolean values then use a BitVector32. If you need to store more then evaluate your needs and coding conditions before blindly picking BitVector32, otherwise you might make more work for yourself reinventing BitArray and not see any of the performance benefits.

Note: in most cases I prefer using a flagged enum instead of a BitVectore32. See this question for an explanation and some good tricks.

like image 4
Trisped Avatar answered Nov 13 '22 12:11

Trisped