Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi StringBuilder

Tags:

delphi

Exists in Delphi something like the Java or C# StringBuilder? Or Delphi does not need StringBuilder and s := s + 'some string'; is good expression (mainly in for, while loops).

like image 709
user81864 Avatar asked Mar 26 '09 16:03

user81864


4 Answers

Yes, Delphi offers TStringBuilder (since version 2009):

procedure TestStringBuilder;
var
  I: Integer;
  StringBuilder: TStringBuilder;
begin
  StringBuilder := TStringBuilder.Create;
  try
    for I := 1 to 10 do
    begin
      StringBuilder.Append('a string ');
      StringBuilder.Append(66); //add an integer
      StringBuilder.Append(sLineBreak); //add new line
    end;

    OutputWriteLine('Final string builder length: ' +
                    IntToStr(StringBuilder.Length));
  finally
    StringBuilder.Free;
  end;
end;

And yes, you are right. s := s + 'text'; isn't really slower than using TStringBuilder.

like image 199
ulrichb Avatar answered Nov 08 '22 10:11

ulrichb


In older Delphis, you can use Hallvard Vassbotn's HVStringBuilder. I failed to find the sources on his blog, but you can fetch them in the OmniThreadLibrary source tree, for example (you'll need files HVStringBuilder.pas and HVStringData.pas).

like image 30
gabr Avatar answered Nov 08 '22 08:11

gabr


The TStringBuilder mentioned is the way to go. In your specific case concatenation may be fine, but I'd always try the alternative anyway.

I am creating an EPUB body content xhtml file in memory (Delphi XE) and it was taking so long to produce it that I never once let it finish (about 5 minutes plus before abandoning). This is a real life example combining around 800,000 characters of text. Taking the EXACT same code and directly replacing the s:=s+'' style statements with TStringBuilder.Append statements reduced it to around 3 seconds. To reiterate, there were no logic changes beyond a switch away from concatenation.

like image 5
Anon Avatar answered Nov 08 '22 08:11

Anon


Delphi does not "REQUIRE" a string builder class, but one is provided for Delphi 2009 if you so desire to use it. Your example of s := s + 'some string'; is a typical method of concatinating strings and has been used in Pascal/Delphi for the past few decades without any significant problems.

like image 6
skamradt Avatar answered Nov 08 '22 08:11

skamradt