While doing memory analysis on one of my scenarios, I noticed that System.Collections.BitArray.BitArrayEnumeratorSimple::get_Current Object () is doing lot of allocations of System.Boolean object.

I wrote a simple program to reproduce the behavior and as it turns out, for BitArray object returning an enumerator by calling foreach operator does allocate a lot of memory. In a simple test of 1000 entries in BitArray object, enumerating over the entries 1000 times resulted in 11,767,392 bytes of allocations for 980,616 instances of System.Boolean object. The total allocations for the scenario were 11.49 MB. The total time for executing the scenario was 35.120 ms.

bool b;

BitArray newBitArray = new BitArray(1000, false);

for (int j = 0; j < 1000; j++)

{

foreach (bool b2 in newBitArray)

    {

        b = b2;

    }

}

I changed the code to access the properties based on index rather than getting enumerator over the BitArray object. The allocations to System.Boolean object disappeared and the total allocations for the scenario reduced to 23.52kB. The time for execution came down to 8.189 ms.

bool b;

BitArray newBitArray = new BitArray(1000, false);

for (int j = 0; j < 1000; j++)

{

for (int i = 0; i < newBitArray.Count; i++)

    {

        b = newBitArray[i];

    }

}

So there you go. Watch for BitArray.GetEnumerator() in your code.

In case you are wondering, I used CLR Profiler for analysis. You can download this for free from here.

Update: Added file for sample program