This week I found a new interesting piece of code. Someone wanted to initialize a string with a special length of the same char.
1 2 3 4 5 6 7 8 9 10 11 12 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
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.
1 2 3 4 5 6 7 8 9 10 11 |
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.
1 2 3 4 5 6 7 8 9 |
const cBufferLength = 100; var I: Integer; begin ... FBuffer := StringOfChar(' ', cBufferLength) ... end; |