Is manually calling SetLength(array, 0); having a drawback?

291 Views Asked by At

I always pair my initialization of a dynamic array with a finalizer in the form of

finally 
  SetLength(Array, 0); 
end;

It feels more natural to know exactly when the array gets "destroyed" and allows me smoother transition from arrays to TList if needed by already having a "finally" available.

Yet that approach makes the source code more indented. Is there any drawback in this approach - readability, maintainability, extensibility, performance, error prroness?

Sample code I write:

var
  A1: array of Integer;
  A2: array on Boolean;
  A3: array of string;
begin
  SetLength(A1, 10);
  try
    ...
    SetLength(A2, 20);
    try
      ...
      SetLength(A3, 30);
      try
        ...
      finally
        SetLength(A3, 0);
      end;
    finally
      SetLength(A2, 0);
    end;
  finnally
    SetLength(A1, 0);
  end;
end;
1

There are 1 best solutions below

1
On BEST ANSWER

Is there any drawback in this approach - readability, maintainability, extensibility, performance, error proneness?

Readability: definitely!

Maintainability, extensibility: As you say, this would make the transition to a TList simpler. But how often do you start off with an array and later convert it to a TList?

Performance: The compiler already does exactly what you're doing. Now it's happening twice. The redundant calls to SetLength when there's nothing to do have minimal overhead, but (in 32-bit at least) those try-finally blocks have some noticeable overhead to them.

Error proneness: Anytime you do something manually that the compiler can handle for you, there's a certain chance you could make a mistake. How often that actually happens is something you would know better than me, but statistically, yes, you increase error proneness by doing this.