tags:

views:

459

answers:

1

The documentation says that CSimpleArray is for dealing with small numbers of objects. What is small in this context? Is CSimpleArray ever a good choice or should I always use a different collection class such as CAtlArray?

A: 

"Small" here is a rule of thumb, which stems from the way the two classes manage their memory internally. Basically, CAtlArray provides more fine-grained control of the memory it uses, and CSimpleArray deals with memory simply but naively.

Specifically, when an element is added to a CSimpleArray, if the array already uses all the memory it has allocated, it will double its size, which is a fairly expensive operation. A newly created CSimpleArray will start with space for 0 items. So let's say you want to add 5 things to an array. It will look like this:

  • Add 1st item - there is no room, so reallocate space for 1 item in total
  • Add 2nd item - there is no room, so reallocate space for 2 items in total
  • Add 3rd item - there is no room, so reallocate space for 4 items in total
  • Add 4th item - there is room, so just add
  • Add 5th item - there is no room, so reallocate space for 8 items in total
  • and so on...

Also note that there is no way to specify the initial size of a CSimpleArray, so this patten will always happen.

On the other hand, a CAtlArray allows you to specify the allocated memory all at once, via the SetCount( ) method. Using the same example as above, before adding the items, call SetCount(5). Then there will always be room for 5 items and no reallocations need to be done.

So to answer the question: use CAtlArray if you care about memory management, especially if you are worried abot performance. Use CSimpleArray if you just want to keep a few items in a list and don't care how the memory the list occupies is managed. To answer the specific question about what "small" and "large" mean in this context, "small" means few enough elements that it's ok with you to reallocate every time the length exceeds the next power of 2.

It's also worthwhile to note that CSimpleArray lets you search through the Array using the Find( ) method, and CAtlArray does not.

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

Sam S