Search code examples
c++mfcdynamic-arrays

CArray and memory pre-allocation


I'm working with the code in a MFC project that uses CArray class to work with dynamic arrays. It works as such:

CArray<CUSTOM_STRUCT> arr;
while(some_criteria)
{
    CUSTOM_STRUCT cs;
    add.add(cs);
}

This approach works, but becomes really slow with a large number of additions to dynamic array. So I was curious, is there a way to preallocate memory in CArray before I begin calling the add() method?

There's one caveat though. I can only estimate approximately the resulting number of elements in the array before I go into my while() loop.

PS. I cannot use any other arrays than CArray.

PS2. Due to complexity of this prokect, I would prefer to keep additions to the array via the add() method.


Solution

  • Really, really consider swapping out for a std::vector. It is surprisingly easy.

    This is an attempt to make CArray follow a std::vector-like growth policy, instead of by 1 each time:

    CArray<CUSTOM_STRUCT> arr;
    while(some_criteria) {
      CUSTOM_STRUCT cs;
      arr.SetSize( arr.GetSize(), 1 + arr.GetSize()/2 );
      arr.add(cs);
    }
    

    When I run into this problem, I replace the CArray with a std::vector, so I haven't tested the above. Reading the docs, it should work. Test it and see if you get a massive performance increase (it should go from O(n^2) down to O(n) amortized)).