StringReplace alternatives to improve performance

前端 未结 8 886
温柔的废话
温柔的废话 2021-02-04 12:46

I am using StringReplace to replace > and < by the char itself in a generated XML like this:

StringReplace(xml.Text,\'>\',\'>\',[rfReplaceA         


        
8条回答
  •  醉酒成梦
    2021-02-04 13:31

    If you're using Delphi 2009, this operation is about 3 times faster with TStringBuilder than with ReplaceString. It's Unicode safe, too.

    I used the text from http://www.CodeGear.com with all occurrences of "<" and ">" changed to "<" and ">" as my starting point.

    Including string assignments and creating/freeing objects, these took about 25ms and 75ms respectively on my system:

    function TForm1.TestStringBuilder(const aString: string): string;
    var
      sb: TStringBuilder;
    begin
      StartTimer;
      sb := TStringBuilder.Create;
      sb.Append(aString);
      sb.Replace('>', '>');
      sb.Replace('<', '<');
      Result := sb.ToString();
      FreeAndNil(sb);
      StopTimer;
    end;
    
    function TForm1.TestStringReplace(const aString: string): string;
    begin
      StartTimer;
      Result := StringReplace(aString,'>','>',[rfReplaceAll]) ;
      Result := StringReplace(Result,'<','<',[rfReplaceAll]) ;
      StopTimer;
    end;
    

提交回复
热议问题