2017-02-25 21 views
2

使用TList作爲記錄容器。申請時,TList增加和刪除大量的記錄。但在delete之後,屬性capacity決不會減少,並且內存不會釋放。如何解決這個問題? 簡單化的代碼示例:在刪除TList <>項目後如何正確釋放內存?

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

回答

5

documentation on TList.Pack

此過程從列表中刪除T類的任何物品與爲默認值T的值。

The co你發佈表明你似乎認爲這會減少名單Capacity,但這不是這個。你應該使用的是TList.TrimExcessFrom the docu

TrimExcess設置計數容量,擺脫列表中的所有多餘容量。

+0

這正是我所需要的。謝謝! – HeathRow

2

你可以寫

MyList.Capacity := MyList.Count;