Does setting a local dynamic array's length to zero reduce memory usage?

245 views Asked by At

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;
2

There are 2 answers

0
Andreas Rejbrand On BEST ANSWER

In Delphi, dynamic arrays are reference-counted.

Thus, if you do

MyArray := nil;

or

Finalize(MyArray);

or

SetLength(MyArray, 0);

the variable MyArray will 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

var
  a: array of Integer;
begin

  SetLength(a, 1024*1024);

  // ...

  SetLength(a, 0);

  // ...

end

you will free up the memory on SetLength(a, 0), assuming a is the only variable pointing to this heap object.

Example 2

var
  b: TArray<Integer>;

procedure Test;
var
  a: TArray<Integer>;
begin

  SetLength(a, 1024*1024);

  b := a;

  SetLength(a, 0);

  // ...

end

SetLength(a, 0) will not free up any memory, because b is still referring to the original array. It will reduce the reference count from 2 to 1, though.

Example 3

And, of course, in

var
  a: array of Integer;
begin

  SetLength(a, 1024*1024);

  // ...

  SetLength(a, 0);

end

the last call to SetLength is completely unnecessary, since the local variable a will go out of scope on the next line of code anyway, which also reduces the refcount of the heap object.

1
HeartWare On

Yes, when you set the length of a dynamic array to zero, the memory it is using is released back onto the available heap memory if no other variable/object is referencing the memory (not necessarily back to Windows memory, so you may not see the benefit in Task Manager, but it'll take longer for your Delphi program to need to allocate additional memory from Windows since it will first use the available heap memory, to which you have added the size of "MyArray").