简体   繁体   中英

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.

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)).

Use CArray::SetSize() method to preallocate the memory.

Please note if the memory is preallocated you should use CArray::operator[] instead of CArray::Add method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM