Why BitVector 32 structure is more efficient than BitArray?
Asked Answered
R

3

17

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

Rockandroll answered 24/5, 2009 at 11:10 Comment(0)
A
18

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.

Amazonite answered 24/5, 2009 at 11:27 Comment(0)
B
9

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

Basic answered 24/5, 2009 at 11:20 Comment(2)
But in BitVector32 also we create an intance of that type. BitVector32 newVector = new BitVector32(4); //like this.Rockandroll
@Rockandroll » A new instance of a struct doesn't have the same overhead as an instance of a class.Cypriot
Y
5

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.

Yvoneyvonne answered 13/2, 2013 at 20:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.