[fpc-devel] static vs dynamic arrays

Michael Van Canneyt michael at freepascal.org
Tue Apr 4 15:01:01 CEST 2006



On Tue, 4 Apr 2006, ???? ??????????? wrote:

>> If you really want to speed up both cases you need to use pointers and
>> increase the pointer value in each iteration. This saves the indexing in
>> every iteration.
>
> Thank you, that was informative. Here are the results (one program at the end for completeness):
>            ap^:=app^; inc(ap); dec(bp);
> 4780    4845
>            ap^:=1; inc(ap);
> 3703    3703
>            ap^:=a[0] xor ap^; inc(ap);
> 3813    4203
>
> Now the question rises again in the original form (not very correct, see previous messages):
> WHY DYNAMICS ARE SLOWER?

Because of the copy-on-write mechanism. The reference count must be
checked each time you do a write. This is normal. It's the same in
Delphi, and a good reason for avoiding dynamic arrays.

You can use pointer arithmetics in FPC, it works as a dynamic array, but
without the overhead.

i.e.

MyArray : PInteger;

begin
   // Equivalent to setlength(MyArray,ArraySize);
   GetMem(MyArray,SizeOf(Integer)*ArraySize);
   Try
     For I:=0 to ArraySize-1 do
       MyArray[i]:=SomeThing;
   Finally
     // Equivalent to setlength(MyArray,0);
     FreeMem(MyArray);
   end;
end;


Michael.



More information about the fpc-devel mailing list