本文整理自网络,侵删。
一、在Setlength 被调用次数不多时,可直接使用以下代码进行释放varaa: array of integer;
procedure TForm1.Button1Click(Sender: TObject);varI: Integer;beginSetLength(aa, 1000);for I := 0 to 999 dobeginaa[I] := i;end;end;
procedure TForm1.Button2Click(Sender: TObject);beginSetLength(aa, 0);end;//这样就OK 了二、如果是作为临时变量,赋值给Result作为函数的返回值时,此时除释放bb外,还需释放临时变量aa。
typeTaa=array of Integer;
procedure TForm1.Button3Click(Sender: TObject);var bb : Taa;begin
bb := getaa;SetLength(bb,0); //执行此行,内存无变化end;
function TForm1.getaa:Taa;var i : Integer;beginSetLength(aa,10000000); //如果采用SetLength(Result,10000000); 直接为Result赋值然后返回,则在上面Button3Click可释放内存for i := 0 to 10000000 - 1 dobeginaa[i] := i + 1;end;Result := aa;end;
procedure TForm1.Button2Click(Sender: TObject);beginSetLength(aa,0); //执行此行,内存占用才减少end;
三、当Setlength在for 或while 循环中使用,被频繁调用很多次时,极易抛出EoutOfMemory异常。此时建议将setlengt拿到循环外部使用,或一次性调用,为动态数组或结构分配足够大的空间。--------------------- 作者:北环阳光 原文:https://blog.csdn.net/lotusyangjun/article/details/8203521
相关阅读 >>
Delphi 中的哈希表: thashedstringlist
Delphi twebbrowser:确定带有框架的页面何时完成
更多相关阅读请进入《Delphi》频道 >>