zoukankan      html  css  js  c++  java
  • Delphi Setlength 内存释放总结

    SetLength

      功能说明:设置字符串或动态数组长度。该函数有两个参数。第一个参数为要设置的字符串变量或动态数组变量,第二个参数为指定的长度
      参考实例:
      var
        S: String;
        arrText: array of Char; // 定义一个动态数组
      begin
        SetLength(S, 10); // 当设置后,S变量只能赋值长度为10的字符串。
        SetLength(arrText, 10); // 只有使用SetLength为动态数组分配内存空间后才能使用动态数组。这句代码的作用相当于arrText: array[0..9] of Char
      end;

    一、在Setlength 被调用次数不多时,可直接使用以下代码进行释放

    [delphi] view plain copy
     
    1. var  
    2.   aa: array of integer;  
    3.   
    4. procedure TForm1.Button1Click(Sender: TObject);  
    5. var  
    6.   I: Integer;  
    7. begin  
    8.   SetLength(aa, 1000);  
    9.   for I := to 999 do  
    10.   begin  
    11.     aa[I] := i;  
    12.    end;  
    13. end;  
    14.   
    15. procedure TForm1.Button2Click(Sender: TObject);  
    16. begin  
    17.   SetLength(aa, 0);  
    18. end;  
    19. //这样就OK 了  

    二、如果是作为临时变量,赋值给Result作为函数的返回值时,此时除释放bb外,还需释放临时变量aa。

    [delphi] view plain copy
     
    1.   type  
    2.       Taa=array of Integer;  
    3.   
    4. procedure TForm1.Button3Click(Sender: TObject);  
    5. var bb : Taa;  
    6. begin  
    7.   
    8.     bb := getaa;  
    9.     SetLength(bb,0);   //执行此行,内存无变化  
    10. end;  
    11.   
    12.   
    13. function TForm1.getaa:Taa;  
    14. var i : Integer;  
    15. begin  
    16.     SetLength(aa,10000000);   //如果采用SetLength(Result,10000000); 直接为Result赋值然后返回,则在上面Button3Click可释放内存  
    17.      for i := to 10000000 - do  
    18.      begin  
    19.         aa[i] := i + 1;  
    20.      end;  
    21.      Result := aa;  
    22. end;  
    23.   
    24.   
    25.   
    26. procedure TForm1.Button2Click(Sender: TObject);  
    27. begin  
    28.     SetLength(aa,0);  //执行此行,内存占用才减少  
    29. end;  

    三、当Setlength在for 或while 循环中使用,被频繁调用很多次时,极易抛出EoutOfMemory异常。此时建议将setlengt拿到循环外部使用,或一次性调用,为动态数组或结构分配足够大的空间。

  • 相关阅读:
    【leetcode】1020. Partition Array Into Three Parts With Equal Sum
    【leetcode】572. Subtree of Another Tree
    【leetcode】123. Best Time to Buy and Sell Stock III
    【leetcode】309. Best Time to Buy and Sell Stock with Cooldown
    【leetcode】714. Best Time to Buy and Sell Stock with Transaction Fee
    【leetcode】467. Unique Substrings in Wraparound String
    【leetcode】823. Binary Trees With Factors
    【leetcode】143. Reorder List
    【leetcode】1014. Capacity To Ship Packages Within D Days
    【leetcode】1013. Pairs of Songs With Total Durations Divisible by 60
  • 原文地址:https://www.cnblogs.com/tc310/p/5207869.html
Copyright © 2011-2022 走看看