I need to split a string to a TStringList with fixed-length sub-strings.
Currently I use:
procedure StrToStringList(ASource: string; AList: TStrings; AFixedLen: Integer);
begin
Assert(Assigned(AList));
while Length(ASource) > AFixedLen do
begin
AList.Add(LeftStr(ASource, AFixedLen));
Delete(ASource, 1, AFixedLen);
end;
AList.Add(ASource);
end;
This works, but seems to be slow. Any better / faster idea?
Edited: Profiling of the results:
The speed gain is quite impressive. Here are the results of my (subjective) profiling.
Data size: 290KB, FixedLen: 100:
Data size: 2805KB, FixedLen: 100:
I think it is wasteful to modify the input string. Avoid this like this:
var
Remaining: Integer;
StartIndex: Integer;
begin
Remaining := Length(ASource);
StartIndex := 1;
while Remaining > 0 do
begin
AList.Add(Copy(ASource, StartIndex, AFixedLen));
inc(StartIndex, AFixedLen);
dec(Remaining, AFixedLen);
end;
end;
This will reduce the amount of heap allocation, and the copying.
However, I would not be surprised if you observed little gain in performance. In order to perform any serious optimisation we'd likely need to see some example input data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With