Each time you call SetLength , memory is reallocated. Perhaps the whole array needs to be copied to another location. And you who just wanted to add one element to the array!
Basically: never do this. There are two ways out of this. The simplest case is if you know the maximum size of the array in advance:
procedure Example1; var data: array of string; ActualLength: integer; procedure AddElement(const Str: string); begin data[ActualLength] := Str; inc(ActualLength); end; begin ActualLength := 0; SetLength(data, KNOWN_UPPER_BOUND); for ... while ... repeat ... AddElement(SomeString); SetLength(data, ActualLength); end;
Here is a practical example of such an approach.
If you donโt know any upper bound a priori, select it in large pieces:
procedure Example2; const ALLOC_BY = 1024; var data: array of string; ActualLength: integer; procedure AddElement(const Str: string); begin if ActualLength = length(data) then SetLength(data, length(data) + ALLOC_BY); data[ActualLength] := Str; inc(ActualLength); end; begin ActualLength := 0; SetLength(data, ALLOC_BY); for ... while ... repeat ... AddElement(SomeString); SetLength(data, ActualLength); end;
Here is a practical example of such an approach.
source share