Show quoted text 7 lines
[...]
> Is there a penalty for calling SetLength if array already has the length
> we need?
Yes, there's always penalty for operations that you don't need. FPC will
generate normal call, pass arguments, etc. I checked if SetLength with
ansistring detects that requested size is same: It doesn't, it performs
whole allocation and moving.
Not always.
Keep in mind that dynamic arrays have references and the array memory itself is a reference counted structure.
SetLength creates a unique copy of the array, that means an array with reference count 1. If it is already unique nothing is changed. For example:
var
A,B: array of string;
begin
SetLength(A,10); // this allocates, A points to unique array
A[0]:='bla'; // the A array is still unique
SetLength(A,10); // no reallocation
B:=A; // reference count increased to 2, not unique anymore
SetLength(A,10); // reallocation to create a second array, now A
// and B point to two unique arrays
SetLength(A,10); // no reallocation
SetLength(B,10); // no reallocation
end;
Mattias