Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a large TObjectList and deallocating the unused part

I am using a TObjectList (Delphi 2007) to store A LOT of data- I expect to have around 300 thousand elements or even more. However, when a list is created, it's default size is set to store only four elements, then eight if one tries to add a fifth element, then sixteen if one tries to add a ninth element and so forth. The numbers may be off, but I think the workings are correct. The problem with this is that all the elements have to be copied from the deallocated part of the memory to the new memory block where the new extended list migrates. I would like to set a specific initial size and deallocate (or undo the reservation of memory, since reserving and allocating aren't the same thing) any unused space that the list has allocated/reserved. This probably isn't a lot of code, but I think that there should be a permanent, solid reference to this problem in the form of a question and answer.

like image 760
programstinator Avatar asked Oct 17 '12 12:10

programstinator


1 Answers

Set the Capacity to the highest number of elements you expect, fill the list, and then set the Capacity to what you actually used (optional). This avoids all of the allocate/move/allocate/move stuff.

MyList.Capacity := 300000;
// Add 280000 items here

// Optionally, reduce the capacity. It's not important to do so unless
//  you end up with a lot of unused items.
MyList.Capacity := MyList.Count;
like image 110
Ken White Avatar answered Oct 06 '22 23:10

Ken White