Wednesday, August 13, 2008

bool vs bitvector32 in C#

In application sometime you need more boolean fields.Also that memory usage and performance is main concern.

For example you require 50 boolean fields. If you create 50 boolean variable
bool b1,b2,b3....b50;
create array of 50 than bool[] b = new bool[50]; then also each bool veriable require 1 byte. so total space usage 50 * 1 = 50bytes.

If you use bitvector32 instead of creating array or 50 variable then it just require 4byte. Each bitvector32 can hold upto 32 different flags.

so for 50 we just need two bitvector32,and space usage reduce to 8 byte instead of 50 byte.

BitArray is also provide functionality like bitvector32 but it is class so it overhead with instance of class, but bitvector32 is simple structure so it reduce that over head too.


BitVector32 bv = new BitVector32(0); This will assign all bits to 0, as 0 binary representation is 00000000000000000000000000000000.

BitVector32 bv = new BitVector32(-1); This will assign all bits set to 1. As –1 binary representation is 11111111111111111111111111111111. (Two’s complement).

You can choose BitArray over BitVector32 when size of array like 40 , 48. That is not in multiple of 32. ( This is just a suggestion).

More information you can find at following location. ref)

1 comment:

Dicky said...

Thanks for the info.