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

How correctly to free the memory after deleting the TList<> items?

使用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));

你可以写

MyList.Capacity := MyList.Count;

来自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.

您发布的代码表明您似乎认为这会减少列表 Capacity,但事实并非如此。

您应该使用 TList.TrimExcessFrom the docu:

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