arraysdelphimemory-managementmemory-optimization

Does setting a local dynamic array's length to zero reduce memory usage?


Does setting a local dynamic array's length to zero (when it's no longer needed) have memory usage benefits?

For example:

var
  MyArray : array of string;
begin
  <filling my array with a lot of items....>

  <doing some stuffs with MyArray>

  //from here on, MyArray is no more needed, should I set its length to zero?
  SetLength(MyArray, 0);

  <doing other stuffs which doesn't need MyArray...>
end;

Solution

  • In Delphi, dynamic arrays are reference-counted.

    Thus, if you do

    MyArray := nil;
    

    or

    Finalize(MyArray);
    

    or

    SetLength(MyArray, 0);
    

    the variable MyArray will no longer point to the dynamic array heap object, so its reference count will be reduced by 1. If this makes the reference count drop to zero, meaning that no variable points to it, it will be freed.

    Example 1

    So in

    var
      a: array of Integer;
    begin
    
      SetLength(a, 1024*1024);
    
      // ...
    
      SetLength(a, 0);
    
      // ...
    
    end
    

    you will free up the memory on SetLength(a, 0), assuming a is the only variable pointing to this heap object.

    Example 2

    var
      b: TArray<Integer>;
    
    procedure Test;
    var
      a: TArray<Integer>;
    begin
    
      SetLength(a, 1024*1024);
    
      b := a;
    
      SetLength(a, 0);
    
      // ...
    
    end
    

    SetLength(a, 0) will not free up any memory, because b is still referring to the original array. It will reduce the reference count from 2 to 1, though.

    Example 3

    And, of course, in

    var
      a: array of Integer;
    begin
    
      SetLength(a, 1024*1024);
    
      // ...
    
      SetLength(a, 0);
    
    end
    

    the last call to SetLength is completely unnecessary, since the local variable a will go out of scope on the next line of code anyway, which also reduces the refcount of the heap object.