Strings Delphi

Title: Speed-Up String Functions
Question: Avoid concatenation of strings, because it''s rather slow!
Answer:
This is how you should *NOT* implement string functions:
{*********************************************
replace char ch1 by ch2
this function is slow because concatenation
of strings ("Result := Result + ch2") is slow
*********************************************}
function ReplaceCharSlow (const s: string;
ch1: char; ch2: char): string;
var i: integer;
begin
Result := '';
for i := 1 to length (s) do
if s [i] = ch1 then
Result := Result + ch2
else
Result := Result + s [i];
end;
You can avoid string concatenation as well as the
else branch as follows:
{*********************************************
replace char ch1 by ch2,
about 160 times faster!
*********************************************}
function ReplaceCharFast (const s: string;
ch1: char; ch2: char): string;
var i: integer;
begin
Result := s;
for i := 1 to length (Result) do
if Result [i] = ch1 then
Result [i] := ch2;
end;
This is about 160 times faster (tested by calling the function 10,000 times with a 1,000-byte string).