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
like
bool b1,b2,b3....b50;
or
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.

Example:

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.
http://msdn.microsoft.com/en-us/library/system.collections.specialized.bitvector32.aspx
http://msdn.microsoft.com/en-us/library/eahchzkf.aspx(C# ref)

1 comment:

Dicky said...

Thanks for the info.