The Capacity
property is almost ideal because it will allocate the correct number of entries in the internal array. However, it has the unfortunate drawbacks that:
- Newly allocated memory is not initialised.
- The number of elements
Strings.Count
is not updated.
Since the Delphi component architecture refers to the base type TStrings
, you are able to provide your concrete subclass that can support more efficient resizing functionality. E.g. 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 updating Capacity, if there is newly allocated memory, it is initialised using FillChar
. This is much more efficient than adding / deleting items one at a time.
So you could either provide your own independent concrete implementation of a TStrings
subclass, or simply make a copy of Delphi's TStringList
which includes an appropriate SetCount
method.
However that said, I find it unlikely that this section of code will suffer any performance concerns, so your own solution wrapped in appropriate utility methods would suffice. David's answer is also good, though personally I don't consider the "class helper" feature to be that useful. The "old way" of implementing class helpers is much more versatile.