In what situations ATL CSimpleArray is a better choice than CAtlArray

The documentation says that CSimpleArray is designed to work with a small number of objects. What is little in this context? Is CSimpleArray ever a good choice or should I always use another collection class like CAtlArray?

+1


source to share


1 answer


"Small" is a rule of thumb that deals with how two classes manage their memory internally. Basically, CAtlArray provides finer-grained management of the memory it uses, while CSimpleArray deals with memory in a simple but naive way.

In particular, when an element is added to the CSimpleArray, if the array is already using all of the allocated memory, it doubles its size, which is quite an expensive operation. The created CSimpleArray will start with a space for 0 elements. So let's say you want to add 5 objects to an array. It will look like this:

  • Add 1st item - no space, so reallocate space for just 1 item.
  • Add second element - no space, so reallocate space for 2 elements altogether.
  • Add third item - no space, so reallocate space for 4 items in total
  • Add 4th item - there is room, so just add
  • Add fifth element - no space, so reallocate space for 8 elements altogether.
  • etc.

Also note that there is no way to specify the initial size of the CSimpleArray, so this pattern will always take place.



On the other hand, CAtlArray allows you to specify the allocated memory immediately using the SetCount () method. Using the same example as above, call SetCount (5) before adding items. Then there will always be room for 5 items and no reallocation is required.

So, to answer the question: use CAtlArray if you care about memory management, especially if you care about performance. Use CSimpleArray if you just want to keep multiple elements in the list and don't care about how the memory the list is in is managed. To answer the specific question of what โ€œsmallโ€ and โ€œlargeโ€ mean in this context, โ€œsmallโ€ means a few sufficient units that you allow you to reallocate every time the length exceeds the next cardinality 2.

It's also worth noting that CSimpleArray allows you to search for an array using the Find () method, while CAtlArray does not.

(Note: my answer is based only on looking at the ATL source code.)

+1


source







All Articles