[fpc-pascal] Effective memory allocation

Sven Barth pascaldragon at googlemail.com
Sun Nov 2 19:50:12 CET 2014


Am 02.11.2014 14:55 schrieb "Xiangrong Fang" <xrfang at gmail.com>:
>
> Hi All,
>
> I am programming a Bloom Filter and need a high-performance way to
allocate and wipe large block of memory.  I did the following test:
>
> program getmem;
> {$mode objfpc}{$H+}
> uses epiktimer;
> const
>   SIZE = 1024 * 1024 * 1024;
>   CNT = 10;
> var
>   a: array of Byte;
>   p: Pointer;
>   et: TEpikTimer;
>   i: Integer;
>   t1, t2: TimerData;
> begin
>   et := TEpikTimer.Create(nil);
>   et.Clear(t1); et.Clear(t2);
>   for i := 1 to CNT do begin
>     et.Start(t1);
>     p := GetMemory(SIZE);
> //    SetLength(a, SIZE);
>     et.Stop(t1);
>     et.Start(t2);
>     FillQWord(p^, SIZE div 8, 0);
> //    FillQWord(a[0], SIZE div 8, 0);
>     et.Stop(t2);
>     FreeMem(p);
> //    a := nil;
>   end;
>   WriteLn('Alloc: ', et.Elapsed(t1) / CNT);
>   WriteLn('Clear: ', et.Elapsed(t2) / CNT);
> end.
>
> The result is:
>
> Using GetMemory:
>
> Alloc:  9.4078169999999997E-0001
> Clear:  2.1342020000000002E-0001
>
> Using SetLength:
>
> Alloc:  2.8100000000000000E-0005
> Clear:  7.7497550000000004E-0001
>
> It is understandable that GetMemory() is faster than SetLength(), but why
the difference in FillQWord()?

If you use SetLength the dynamic array consists not only of the array data,
but also of an information record in front of it. This will likely lead to
the data not being aligned correctly (FillQWord works best with 8-Byte
alignment). So what about testing FillDWord or FillChar? Just to see
whether they would be faster.

>
> Also, I usually use pointer to pass block of memory to functions.  How do
I implement a function with the following signature:
>
> procedure MyProc(var Buf; Len: Integer):
>
> I mean, how to handle "var Buf" inside the procedure body?

You need to cast Buf to a pointer if I remember correctly. Take a look at
the implementation of a TStream's descendant's Write method (e.g.
TStringStream) for an example.

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20141102/9159dcca/attachment.html>


More information about the fpc-pascal mailing list