Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringReplace alternatives to improve performance

Tags:

delphi

I am using StringReplace to replace &gt and &lt by the char itself in a generated XML like this:

StringReplace(xml.Text,'>','>',[rfReplaceAll]) ;
StringReplace(xml.Text,'&lt;','<',[rfReplaceAll]) ;

The thing is it takes way tooo long to replace every occurence of &gt.

Do you purpose any better idea to make it faster?

like image 321
Ricardo Acras Avatar asked Sep 26 '08 14:09

Ricardo Acras


2 Answers

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 "&lt;" and "&gt;" 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('&gt;', '>');
  sb.Replace('&lt;', '<');
  Result := sb.ToString();
  FreeAndNil(sb);
  StopTimer;
end;

function TForm1.TestStringReplace(const aString: string): string;
begin
  StartTimer;
  Result := StringReplace(aString,'&gt;','>',[rfReplaceAll]) ;
  Result := StringReplace(Result,'&lt;','<',[rfReplaceAll]) ;
  StopTimer;
end;
like image 187
Bruce McGee Avatar answered Oct 20 '22 23:10

Bruce McGee


Try FastStrings.pas from Peter Morris.

like image 37
Germán Estévez -Neftalí- Avatar answered Oct 20 '22 23:10

Germán Estévez -Neftalí-