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:
- TStringBuilder.Create and Append pattern which adds new characters to the buffer of the TStringBuilder instance.
- TStringList.Create and Add pattern which adds new lines the to the Text of the TStringList instance.
- The Format function to assemble strings based on format patterns.
- Simple concatenation of string types for expressions with 3 or less values.
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 forAppend
, and also has AppendLine (with only two overloads) if you want to add lines likeTStringList.Add
canTStringBuilder
reallocates the underlying buffer with an over capacity scheme, which means that with large buffers and frequent appends, it can be a lot faster thanTStringList
- 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.
Filed under: Delphi, Delphi 1, Delphi 2, Delphi 2005, Delphi 2006, Delphi 2007, Delphi 2009, Delphi 2010, Delphi 3, Delphi 4, Delphi 5, Delphi 6, Delphi 7, Delphi 8, Delphi x64, Delphi XE, Delphi XE2, Delphi XE3, Delphi XE4, Development, Software Development