The Capacity property is almost perfect, because it will allocate the correct number of records in the internal array. However, it has unfortunate flaws that:
- Recently allocated memory is not initialized.
- The number of
Strings.Count elements is not updated.
Since the architecture of the Delphi component is of the base type of TStrings , you can provide your own specific subclass that can support more efficient resizing functions. For instance. consider the following implementation of TList.SetCount .
procedure TList.SetCount(NewCount: Integer); var I: Integer; begin if (NewCount < 0) or (NewCount > MaxListSize) then Error(@SListCountError, NewCount); if NewCount > FCapacity then SetCapacity(NewCount); if NewCount > FCount then FillChar(FList^[FCount], (NewCount - FCount) * SizeOf(Pointer), 0) else for I := FCount - 1 downto NewCount do Delete(I); FCount := NewCount; end;
After the Capacity upgrade, if there is a newly allocated memory, it is initialized using FillChar . This is much more efficient than adding / removing items one at a time.
So, you can either provide your own independent concrete implementation of the TStrings subclass, or simply make a copy of the Delphi TStringList , which includes the corresponding SetCount method.
However, this suggests that this section of the code is unlikely to have performance problems, so your own solution wrapped in the appropriate utilities will be sufficient. David's answer is also good, although I personally don't find the class helper feature useful. The "old way" to implement class helpers is much more universal.
source share