Do I need to finalize array of records in Delphi?

EProgrammerNotFound picture EProgrammerNotFound · Feb 19, 2013 · Viewed 14.7k times · Source

In my application I have the following record:

TTransaction = record
  Alias: string
  Description: string
  Creation: TDateTime
  Count: Integer
end;

and I'm using this record in this array:

Transactions = array of TTransaction;

I'm keeping the array loaded during runtime, but at a given time I need to clear all data and add some new.

Is it enough just to use:

SetLength(Transactions, 0); ?

Or do I need to finalize something ?

Answer

David Heffernan picture David Heffernan · Feb 19, 2013

There are three ways to deallocate the memory associates with a dynamic array, a:

SetLength(a, 0);
Finalize(a);
a := nil;

It's up to you which one to use.

The documentation says the same, albeit in a slightly round about fashion:

To deallocate a dynamic array, assign nil to a variable that references the array or pass the variable to Finalize; either of these methods disposes of the array, provided there are no other references to it. Dynamic arrays are automatically released when their reference-count drops to zero. Dynamic arrays of length 0 have the value nil.

This will release all memory associated with the array, including any nested managed types, such as strings, dynamic arrys etc. that are owned by your record type.

If you need to resize the array for future use, and have the new data available, simply resize using SetLength, and initialise the remaining elements appropriately.