简体   繁体   中英

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

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

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.

是的,当您将动态数组的长度设置为零时,如果没有其他变量/对象正在引用内存(不一定返回到 Windows 内存,因此您可能看不到),它正在使用的内存将被释放回可用的堆内存任务管理器中的好处,但您的 Delphi 程序需要从 Windows 分配额外的内存需要更长的时间,因为它将首先使用可用的堆内存,您已向其中添加了“MyArray”的大小)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM