简体   繁体   English

将本地动态数组的长度设置为零会减少内存使用吗?

[英]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.在 Delphi 中, 动态数组是引用计数的。

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.变量MyArray将不再指向动态数组堆对象,因此它的引用计数将减少 1。如果这使引用计数降为零,意味着没有变量指向它,它将被释放。

Example 1示例 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 .您将释放SetLength(a, 0)上的内存,假设a是唯一指向此堆对象的变量

Example 2示例 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. SetLength(a, 0)不会释放任何内存,因为b仍然指的是原始数组。 It will reduce the reference count from 2 to 1, though.不过,它会将引用计数从 2 减少到 1。

Example 3示例 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.最后一次调用SetLength是完全没有必要的,因为局部变量a无论如何都会在下一行代码中超出范围,这也减少了堆对象的引用计数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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