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:
- 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
Formatcalls.
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:
TStringBuilderhas many overloads forAppend, and also has AppendLine (with only two overloads) if you want to add lines likeTStringList.AddcanTStringBuilderreallocates 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
TStringBuildercontent, 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 comment