通过 PChar 操作替换字符串分配



我有一个令人费解的结果,我很难理解。

我一直在尝试提高这个例程的速度

function TStringRecord.GetWord: String;
begin
  // return the next word in Input
  Result := '';
  while (PC^ <> #$00) and not PC^.IsLetter do begin
    inc(FPC);
  end;
  while (PC^ <> #$00) and PC^.IsLetter do begin
    Result := Result + PC^;
    inc(FPC);
  end;
end;

通过将Result := Result + PC^替换为基于指针的操作。 这是我的尝试:

function TStringRecord.GetWord2: String;
var
  Len : Integer;
  StartPC,
  DestPC : PChar;
begin
  // return the next word in Input
  Result := '';
  while (PC^ <> #$00) and not PC^.IsLetter do begin
    inc(FPC);
  end;
  Len := Length(Input);
  SetLength(Result, Len);
  StartPC := PChar(Result);
  DestPC := PChar(Result);
  while (PC^ <> #$00) and PC^.IsLetter do begin
    WStrPLCopy(DestPC, PC, 1);
    inc(FPC);
    inc(DestPC);
  end;
  SetLength(Result, DestPC - StartPC);
end;

根据我的线路剖面仪,WStrPLCopy(DestPC, PC, 1)需要 50 倍的时间比Result := Result + PC^. 据我所知,这是因为在进入时对WStrPLCopy有一个调用_WStrFromPWChar似乎复制了更多字符比必要的字符。 我怎样才能避免这种情况,或者有人可以建议另一种基于 PChar 的方法?

我的代码的其余部分如下:

TStringRecord = record
private
  FPC: PChar;
  FInput: String;
  procedure SetInput(const Value: String);
public
  function NextWord : String;
  function NextWord2 : String;
  property Input : String read FInput write SetInput;
  property PC : PChar read FPC;
end;
procedure TStringRecord.SetInput(const Value: String);
begin
  FInput := Value;
  FPC := PChar(Input);
end;

这是我的写法:

function TStringRecord.GetWord: String;
var beg: PChar;
begin
  // return the next word in Input
  while (FPC^ <> #0) and not FPC^.IsLetter do 
    inc(FPC);
  beg := FPC;
  while (FPC^ <> #0) and FPC^.IsLetter do 
    inc(FPC);
  SetString(result, beg, FPC-beg);
end;

有了这个,代码非常可读,并且您只有一个内存分配,我想您无法更快地编写任何内容(但通过内联PC^.IsLetter,这是对外部代码段的唯一调用)。

最新更新