The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,437 other followers

delphi: idioms for building strings (via: my answer on Stack Overflow)

Posted by jpluimers on 2014/04/16

Once every while, one of your StackOverflow answers gets an edit suggestion that is really valuable.

This case it was Edwin Yip who suggested to emphasize the difference between TStringBuilder and TStringList (adding characters versus lines).

Too bad that freshly 10k user Makoto showed he hates bold emphasis, intentional property casing and post signatures by removing the added value (there is so much emphasis he could remove on other answers to warrant at least a day time job).

I know that not all emphasis is welcomed at StackOverflow, but in this case I think it added real value.

So I edited my own answer to add even more value: showing the idioms I use for building strings, and now it is time to quote it:

(Note I removed all the nofollow in the hrefs that StackExchange automatically added)

Basically, I use these idioms for building strings. The most important differences are:

For complex build patterns, the first make my code a lot cleaner, the second only if I add lines and often includes many of Format calls.
The third makes my code cleaner when format patterns are important.
I use the last one only when the expression is very simple.

A few more differences between the first two idioms:

  • TStringBuilder has many overloads for Append, and also has AppendLine (with only two overloads) if you want to add lines like TStringList.Add can
  • TStringBuilder reallocates the underlying buffer with an over capacity scheme, which means that with large buffers and frequent appends, it can be a lot faster than TStringList
  • To get the TStringBuilder content, you have to call the ToString method which can slow things down.

So: speed is not the most important matter to choose your string appending idiom.
Readable code is.

–jeroen

via delphi – When and Why Should I Use TStringBuilder? – Stack Overflow.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: