// JP opened flex table

Click to See Complete Forum and Search --> : SetSize & Add function of CObArray (Bug or Design)


Padmanabhan
July 3rd, 1998, 10:58 AM
Recently I had the oppurtunity to work on COBArray.


I was using the Add function of CObArray to add elements to the Array.

To enhance the performance I called SetSize function of CObArray in

my constructor.


Now when I started to retrieve the elements from the Array using the

Index, I was surprised that the elements where not at that index.


After much struggle I learnt the following :

SetSize function sets a variable in CObArray that specifies the

index of last element in the Array.

Add function uses this variable to position the new element.


For eg :

Initially you could have calls to Add as

Ar.Add(new A); // assuming the element is added to position 0

If you had called Ar.SetSize(200) earlier, the previous call to

Add will put the element at position 201 and not at 0.


From the explaination given in help of MFC, I just thought that

SetSize function helps manage the memory better. But its action

was something different.


I am not sure if this is a bug or it is designed that way.

Bob Wood
July 10th, 1998, 08:56 PM
The MFC documentation is a little grey here but from stepping through the source and experimenting I have come up with the solution that Add is merely a shorthand for:


ArSize = Ar.GetSize();

Ar.SetSize(ArSize + 1);

Ar.SetAt(ArSize, ObVar);


As you can see continually adding elements to the array causes SetSize to be called each time and which in turn causes the array to be extended using realloc. Not very efficient. If you know before hand the number of elements you are adding then it is far better to call the SetSize only once and then call SetAt for each element you are adding. Something like this:


OldArSize = Ar.GetSize();

NewArSize = NewAr.GetSize();

Ar.SetSize(NewArSize + OldArSize);


for (int LoopCount = 0; LoopCount < NewArSize; LoopCount++)

{

Ar.SetAt(OldArSize + LoopCount, NewAr[LoopCount]);

}


I have created some VERY large arrays using CObArray derivatives and believe me the performance enhancement you get by doing it this way is staggering.

//JP added flex table