I’m a bit puzzled of what to use for storing objects in a list.
Until now I have used TList and freed each item in a loop. Then I discovered TObjectList that do this automatically from Free. Then I saw this from the doc of TList.Clear:
Call
Clearto empty the Items array and set theCountto 0.Clearalso
frees the memory used to store theItemsarray and sets theCapacityto 0.
So it is basically the same. So
for TList
mylist.Clear;
myList.Free;
is the same as for TObjectList?
myList.Free;
Can TObjectList only be used for items as classes or can I store records?
1. TList won’t free the elements, with both
ClearorFree.aList.Clear;
Will just set
aList.Count := 0without freeing theaList.Items[]elements. So you’ll leak memory. You’ll need an explicit free as such:But this is what
TObjectListdoes… 🙂About
TObjectList, it is worth saying thatTObjectList.Destroyis callingClear.So
is exactly the same as
2. To store a list of records, you can use a dynamic array.
You’ll get all
TListmethods (and more) with our dynamic array wrapper. That is,Add / Delete / Clear / Count / IndexOf / Find…It has built-in serialization features (in binary or JSON), automated sorting and comparison (using RTTI) which are not existing with a
TList/TObjectList. From Delphi 5 and later.With more modern version of Delphi, you may use generics to handle the dynamic array, if you do not want to use a third-party library.