[fpc-pascal] Array clearing

Jürgen Hestermann juergen.hestermann at gmx.de
Thu Apr 13 16:25:19 CEST 2017

Am 2017-04-13 um 13:17 schrieb MARCOU Gilles:
 > Regarding this code:
 >> SetLength(Array,Length(Array)+1);
 >> Array[High(Array)] := …
 > as I understood from (http://wiki.freepascal.org/Dynamic_array),
 > SetLength will create a copy of the array and free the memory of the shorter array.
 > In this case, a lot of memory operations and copy operations are performed thus
 > degrading the performances of the code. Then it would be unwise to use such strategy:
 > better allocate the size of the array correctly at the beginning of the run,
 > or resize the array by block, to decrease the frequency of such operation:

Yes, that's my knowledge about dynamic arrays too.
Although it *can* happen that the array is not copied
(see answer mail from Sven) in general it will (is forced to)
allocate a new (larger) memory chunk and copy the data over to it.
This is IMO unavoidable if the existing memory area cannot be extended.

There are 2 strategies against it:

1.) If you already know the correct size at the end of an operation you can simply create the array with the final size in the first place.

2.) If you know that the array will be extended many times but you do not know in prior what the final size is,
then you can extend the array in larger slices (16, 32 or whatever).
Then, if the final size is reached, you can remove empty elements with

But very often the performance degrade of Setlength is overvalued.
If the Length variation is done only seldom (compared to other code)
then it's not worth thinking about such optimizations.

Also, I often have dynamic arrays of pointers (strings or other managed types).
In this case the array elements consists of pointers and only the pointers will be copied
but not the data they point to.

More information about the fpc-pascal mailing list