从内存结构到管理机制, String 远比 Char 要复杂.
因此, 面对这种情况(要定位的是 Char) Pos 还有优化的余地; 优化后速度会提升 5 倍左右.
测试效果图:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//自定义的 Pos 函数
function MyPos(c: Char; const str: string): Integer;
var
i: Integer;
begin
Result := 0;
for i := 1 to Length(str) do
if c = str[i] then begin Result := i; Exit end;
end;
{对比测试}
procedure TForm1.Button1Click(Sender: TObject);
var
s: string;
c: Char;
i: Integer;
n: Cardinal;
begin
s := 'abcdefghijklmnopqrstuvwxyz';
Randomize;
c := Chr(Random(26) + 97); {随机一个 a..z 的字符}
{用 Pos 函数}
n := GetTickCount;
for i := 1 to 1000000 do Pos(c,s);
n := GetTickCount - n;
Text := IntToStr(n) + ' - ';
{用自定义的 MyPos 函数}
n := GetTickCount;
for i := 1 to 1000000 do MyPos(c,s);
n := GetTickCount - n;
Text := Text + IntToStr(n);
Button1.Caption := 'Pos 与 MyPos 速度测试';
end;
end.