2

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

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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").

1 Comment

This is not true in general. When you set the length to zero, you reduce the reference count of the heap object. Only if the new refcount is 0 will the heap object be freed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.