Does setting a local dynamic array's length to zero (when it's no longer needed) have memory usage benefits?
For example:
var
MyArray : array of string;
begin
<filling my array with a lot of items....>
<doing some stuffs with MyArray>
//from here on, MyArray is no more needed, should I set its length to zero?
SetLength(MyArray, 0);
<doing other stuffs which doesn't need MyArray...>
end;
In Delphi, dynamic arrays are reference-counted.
Thus, if you do
or
or
the variable
MyArraywill no longer point to the dynamic array heap object, so its reference count will be reduced by 1. If this makes the reference count drop to zero, meaning that no variable points to it, it will be freed.Example 1
So in
you will free up the memory on
SetLength(a, 0), assumingais the only variable pointing to this heap object.Example 2
SetLength(a, 0)will not free up any memory, becausebis still referring to the original array. It will reduce the reference count from 2 to 1, though.Example 3
And, of course, in
the last call to
SetLengthis completely unnecessary, since the local variableawill go out of scope on the next line of code anyway, which also reduces the refcount of the heap object.