[fpc-devel] Growing a memory stream

Michael Van Canneyt michael at freepascal.org
Mon Dec 11 17:05:23 CET 2006



On Mon, 11 Dec 2006, Vincent Snijders wrote:

> Hi,
> 
> Currently the TMemoryStream grows in steps of 4096 bytes.
> 
> When writing 100000 chunks of say 80 bytes to it, this causes a lot of
> reallocations. I think it is better to grow at least a quarter for example.
> 
> The new code could look something like:
> function TMemoryStream.Realloc(var NewCapacity: Longint): Pointer;
> 
> begin
>   // round off to block size.
>   If NewCapacity<0 Then
>     NewCapacity:=0
>   else begin
>     if NewCapacity - Capacity < Capacity div 4 then
>     	NewCapacity := Capacity + Capacity div 4;
>     NewCapacity := (NewCapacity + (TMSGrow-1)) and not (TMSGROW-1);
>   end;
>   // Only now check !
>   If NewCapacity=FCapacity then
>     Result:=FMemory
>   else
>     begin
>       Result:=Reallocmem(FMemory,Newcapacity);
>       If (Result=Nil) and (Newcapacity>0) then
>         Raise EStreamError.Create(SMemoryStreamError);
>     end;
> end;
> 
> What do you think?

I don't see a problem with that. A similar mechanism is used to TStringList.

Michael.



More information about the fpc-devel mailing list