[fpc-devel] TBytes
Mattias Gaertner
nc-gaertnma at netcologne.de
Tue Feb 28 09:41:38 CET 2012
On Tue, 28 Feb 2012 09:23:34 +0100
Sven Barth <pascaldragon at googlemail.com> wrote:
> Am 28.02.2012 05:04, schrieb Martin Schreiber:
> > Hi,
> > I read that we should use TBytes instead of AnsiString in order to
> > implement combined binary/character buffers with automatic memory
> > management. With AnsiString we used setlength() in order to allocate not
> > initialized memory.
> > TBytes is defined as
> > "
> > TBytes = array of Byte;
> > "
> > where setlength() fills the buffer with zeros. What should we use instead?
>
> For strings SetLength also fills the string with zeros as the following
> example shows:
>
> === example begin ===
>
> program setlengthtest;
>
> var
> barr: array of Byte;
> b: Byte;
> s: AnsiString;
> c: Char;
> begin
> SetLength(barr, 20);
> for b in barr do
> Write(b, ' ');
> Writeln;
> SetLength(s, 20);
> for c in s do
> Write(Ord(c), ' ');
> Writeln;
> end.
>
> === example end ===
>
> === output begin ===
>
> PS P:\tests\oneshots> .\setlengthtest.exe
> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
That's because the OS gives you on first time a lot of zeroed mem.
SetLength does not zero memory. Try this:
var
i: Integer;
s: string;
begin
for i:=1 to 100000 do begin
SetLength(s,1000000); // size does not matter for speed
SetLength(s,1);
end;
end.
Mattias
More information about the fpc-devel
mailing list