我需要将一个字符串拆分为具有固定长度子字符串的 TStringList。
目前我使用:
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;
这有效,但似乎很慢。有更好/更快的想法吗?
编辑:结果分析:
速度增益相当可观。
这是我的(主观)分析的结果。
数据大小:290KB,固定长度:100:
- 原始代码:58 毫秒
- 赫弗南:1 毫秒
- 三角肌:1 毫秒
数据大小:2805KB,固定长度:100:
- 原始代码:5803 毫秒
- 赫弗南:5 毫秒
- 三角肌:4 毫秒
我认为修改输入字符串是浪费。像这样避免这种情况:
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;
这将减少堆分配和复制的数量。
然而,如果您观察到性能几乎没有提高,我不会感到惊讶。为了执行任何认真的优化,我们可能需要查看一些示例输入数据。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)