Re: How can I use CArray efficiently?
"Doug Harrison [MVP]" <dsh@mvps.org> wrote in message
news:qmlk13d64admqvboj63vbsc7p7jcb7p9ik@4ax.com...
I think you must be mistaken. Not even an MFC class could be so
unintuitive
as to define a member SetSize that sets the capacity and a member GetSize
that returns the size.
You're right, as the fellow who actually did the test and printed out the
results confirmed. (I was confusing CArray with CHashTable, which also has
an init size method.) Well then, this is quite confusing. If SetSize(100)
is called to allocate the first 100 elements so they will be stored quickly,
then GetSize() returns 100. But then how to iterate the array to visit all
items? The doc gives the example of using GetSize()!
CTypedPtrArray<CObArray, CPerson*> myArray;
for( int i = 0; i < myArray.GetSize();i++ )
{
CPerson* thePerson = myArray.GetAt( i );
...
}
So even if zero items are added, this loop still executes 100 times! I
wonder what GetAt() returns for these non-existant items? I guess I should
find out, but I guess I've not used SetSize() before ...
It's still a linear growth policy and thus insignificant in the long run,
becoming ultimately glacial at some point depending on machine speed and
whether or not the underlying allocator can extend in place. The solution
is to use an exponential growth policy, such as std::vector has been
required to use all along. See the subthread beginning here for more on
this:
.... and perhaps the reason is perhaps it's not necessary in later versions
of MFC. The doc says, about nGrowBy parameter: "If the default value is
used, MFC allocates memory in a way calculated to avoid memory fragmentation
and optimize efficiency for most cases."
So maybe MFC also implements exponential growth policy in the default case?
Again, I really should find out but am too busy at the moment.
-- David