As a followup to the String Concatenation article, let’s take a look at a less trivial case: what if instead of concatenating a couple strings, you want to concatenate a few hundred?
Sounds like a task at which TStringBuilder should excel, but one should never assume, and always measure.
Eating Lots of Apples
While some drink bottles of beer, we will eat apples instead.
Here is the Trivial version
Result := ''; for i := 1 to NB do Result := Result + #13#10'Eating apple #' + IntToStr(i);
The TStringBuilder and other object version are a bit longer, but to keep things short, I’m not reproducing the variable declarations or the try..finally for constructor/destructor.
for i := 1 to NB do sb.Append(#13#10'Eating apple #').Append(i); Result := sb.ToString;
I made two variants, one without pre-allocation, and another with pre-allocated buffer (through the Capacity property).
Similarly, you can have a TStringStream version (using WriteString in place of Append, and ToString with DataString).
Finally for the Format function lovers there is a Trivial Format as well
Result := ''; for i := 1 to NB do Result := Result + Format('#13#10'Eating apple #%d', [i]);
And just for the fun of it, I made a version with DWScript‘s TWriteOnlyBlockStream (yes, that is a mouthful) whose code is similar to the TStringBuilder and TStringStream contenders.
Okay, ladies and gentlemen, place your bets, let the drums roll end and let’s see the benchmark results.