[Lazarus] Questions about SetLength

Mattias Gaertner nc-gaertnma at netcologne.de
Sat Sep 13 00:38:59 CEST 2014

On Fri, 12 Sep 2014 19:21:45 +0200
payl <payl at wp.pl> wrote:

> > 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:

  A,B: array of string;
  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


More information about the Lazarus mailing list