gpt4 book ai didi

delphi - 删除 TList<> 项后如何正确释放内存?

转载 作者:行者123 更新时间:2023-12-03 15:46:08 24 4
gpt4 key购买 nike

使用TList作为记录容器。在应用过程中,TList添加和删除大量记录。但在delete之后,属性capacity永远不会减少,内存也不会被释放。怎么解决这个问题呢?简单的代码示例:

type
TMyRecord = record
Num : integer;
Str : String
end;

var
MyRecord : TMyRecord;
MyList :TList<TMyRecord>;



MyList := TList<TMyRecord>.Create;

MyRecord.Num := 1;
MyRecord.Str := 'abc';

for i := 0 to 63 do
begin
MyList.Add(MyRecord);
end;

Memo1.Lines.Add('Before deleting');
Memo1.Lines.Add('Count='+IntToStr(MyList.Count));
Memo1.Lines.Add('Capacity='+IntToStr(MyList.Capacity));

for i := 0 to 59 do
begin
MyList.Delete(0);
end;

MyList.Pack; // Here need to somehow free the memory.

Memo1.Lines.Add('After deleting');
Memo1.Lines.Add('Count='+IntToStr(MyList.Count));
Memo1.Lines.Add('Capacity='+IntToStr(MyList.Capacity));

最佳答案

来自documentation on TList.Pack :

This procedure removes from the list any item of class T with a value that is the default value of T.

您发布的代码表明您似乎认为这会减少列表容量,但这不是目的。

您应该使用的是TList.TrimExcessFrom the docu :

TrimExcess sets Capacity to Count, getting rid of all excess capacity in the list.

关于delphi - 删除 TList<> 项后如何正确释放内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42458225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com