StringOfChar

This week I found a new interesting piece of code. Someone wanted to initialize a string with a special length of the same char.

procedure TMyClass.Init;
const
  cBufferLength = 100;
var
  I: Integer;
begin
  ...
  FBuffer := ''
  for I := 1 to cBufferLength do
    FBuffer := FBuffer + ' ';
  ...
end;

Come on guys, this is complete rubbish! In short words, a string is a record that allocs as much memory as the string needs. With this for loop the poor memory manager has to alloc a piece of memory 100 times! As you can image this is not fast and will also turn your memory into small pieces.

procedure TMyClass.Init;
const
  cBufferLength = 100;
var
  I: Integer;
begin
  ...
  SetFBuffer := ''
  for I := 1 to cBufferLength do
    FBuffer := FBuffer + ' ';
  ...
end;

A better solution would be to set the length of the string and then to set all chars.

const
  cBufferLength = 100;
var
  I: Integer;
begin
  ...
  SetLength(FBuffer, cBufferLength);
  for I := 1 to cBufferLength do
    FBuffer[I] := ' ';
  ...
end;

Or simply call the StringOfChar function.

const
  cBufferLength = 100;
var
  I: Integer;
begin
  ...
  FBuffer := StringOfChar(' ', cBufferLength)
  ...
end;
This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.