在Delphi中将字符串拆分成固定长度的部分的快捷方式 [英] Fast way to split a string into fixed-length parts in Delphi

查看:272
本文介绍了在Delphi中将字符串拆分成固定长度的部分的快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个字符串拆分成具有固定长度子字符串的TStringList。

I need to split a string to a TStringList with fixed-length sub-strings.

目前我使用:

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?

已编辑:分析结果

速度获得相当令人印象深刻。
这是我(主观)剖析的结果。

The speed gain is quite impressive. Here are the results of my (subjective) profiling.

数据大小:290KB,固定线路:100:

Data size: 290KB, FixedLen: 100:


  • 原始码:58 ms

  • Heffernan:1 ms

  • Deltics:1 ms

数据大小:2805KB,FixedLen:100:

Data size: 2805KB, FixedLen: 100:


  • 原始码:5803 ms

  • Heffernan:5 ms

  • Deltics:4 ms

推荐答案


  1. 不要修改源字符串,只需提取所需的
    子串。然后,您可以输入字符串参数const,
    ,允许编译器进一步优化对过程的调用

  1. Do not modify the source string, simply extract the required substrings. You can then make the input string parameter const, allowing the compiler to further optimise calls made to the procedure

由于您正在处理固定长度和
已知长度的输入字符串,那么您可以预先计算
的字符串列表的所需容量,并避免内存重新分配,因为列表中添加

Since you are dealing with fixed lengths and an input string of known length, then you can pre-calculate the required capacity of the string list and avoid memory re-allocations as the list is added to.

以下是我将如何处理:

procedure StrToStringList(const aSource: String;
                          const aList: TStrings;
                          const aFixedLen: Integer);
var
  idx: Integer;
  srcLen: Integer;
begin
  aList.Capacity := (Length(aSource) div aFixedLen) + 1;

  idx    := 1;
  srcLen := Length(aSource);

  while idx <= srcLen do
  begin
    aList.Add(Copy(aSource, idx, aFixedLen));
    Inc(idx, aFixedLen);
  end;
end;

这里的容量计算可能会导致额外容量为1,其中输入字符串正好与固定长度,但这是可忽略的开销imho和可接受的目标是最佳性能(替代方案是有条件的分支来修改或计算容量不同以满足可能是少数情况)。

The capacity calculation here may result in an excess capacity of 1 where the input string divides exactly by the fixed length, but this is a negligible overhead imho and acceptable where the goal is optimal performance (the alternative is a conditional branch to modify or calculate the capacity differently to cater for what is likely to be the minority of cases).

这篇关于在Delphi中将字符串拆分成固定长度的部分的快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆