Bitarray VS bool[]

Byyo picture Byyo · Nov 3, 2015 · Viewed 9.3k times · Source

I expected to find a existing question here on SO about this but i didn't.

What is the advantage of using a Bitarray when you can store your bool values in a bool[]?

System.Collections.BitArray biArray = new System.Collections.BitArray(8);
biArray[4] = true;

bool[] boArray = new bool[8];
boArray[4] = true;

The bool[] seems a little more handy to me because there exist more (extension)methods to work with a array instead of a BitArray

Answer

Kvam picture Kvam · Nov 3, 2015

There's a memory/performance tradeoff. BitArray will store 8 entries per byte, but accessing a single entry requires a bunch of logical operations under the hood. A bool array will store each entry as one byte and thus taking up more memory, but requiring fewer CPU cycles to access.

Essentially, BitArray is a memory optimization over bool[], but there's no point in using it unless memory is sparse.

Edit: Created a simple performance test. Inversing 500M elements using BitArray takes 6 seconds on my machine:

const int limit = 500000000;
var bitarray = new BitArray(limit);
for (var i = 0; i < limit; ++i)
{
    bitarray[i] = !bitarray[i];
}

The same test using a bool array takes about 1.5 seconds:

const int limit = 500000000;
var boolarray = new bool[limit];
for (var i = 0; i < limit; ++i)
{
    boolarray[i] = !boolarray[i];
}