views:

154

answers:

1

System.BitArray only implements the non-generic IEnumerable, which returns an Object for the IEnumerator.Current property. Does running a foreach over a BitArray - eg

foreach (bool b in bitArray)
{
    // ...
}

box and unbox each and every bit value?

Looking at the bitarray enumerator in reflector, it looks like it does a fresh bitmask on every call of MoveNext() rather than something cleverer. Is there a more efficient way of enumerating a BitArray, or a replacement for BitArray that has the same storage characteristics? (List<bool> etc uses one byte per bool, rather than a single bit, so uses 8x as much space)

+4  A: 

Yes, it will cause a lot of boxing. However, in most cases I wouldn't actually expect that to hurt performance too much. It's annoying, but I doubt that many real world apps spend a significant amount of time boxing/unboxing (or cleaning up the boxes afterwards, which is the other cost of course). It's probably worth checking that before you go to any great effort to avoid it.

You could write your own iterator over it fairly easily though... particularly if you didn't care about breaking if the "version" changes. For example:

public static IEnumerable<bool> EnumerateBitArray(BitArray bitArray)
{
    for (int i=0; i < bitArray.Length; i++)
    {
        yield return bitArray[i];
    }
}

Bad things will almost certainly happen if you do change the array while you're iterating though - particularly if you change the length!

Jon Skeet