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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With