TStringBuilder is a new class of Delphi 2009 that mimicks the StringBuilder class of .NET. There have already been many reference in various blgos (from CodeGear developers) hinting at the idea that using the TStringBuilder class is faster than concatenating strings. Last week Olaf Monien posted a TStringBuilder benchmark along that same line, and that surprised me, because in my experience the TStringBuilder class isn't that fast. So who is right?

I think we are both right. In his code (you can download the project from his blog) he adds a single character to the string or TStringBuilder:

SB.Append(' ');
s := s + ' ';

and the former is indeed faster. In my test: 3,151 for TStringBuilder vs. 3,837 for a plain concatenation. I was indeed surprised. Than I noticed there is a specific overload of the Append method that takes as parameter a Char and has specific optimized code. If you alter the original source code slightly, adding a new string that takes the single space as value, and append or concatenate the string, with the lines:

s2 := ' ';
s := s + s2;

The timing changes dramatically, with 11,170 for TStringBuilder vs. 3,791 for a plain concatenation (notice the latter does not change at all). And I've enabled the various string-processing optimizations Delphi 2009 provides (at least $StringChecks OFF, which makes a minor but noticeable difference, cutting about 500 ticks).

In other words, this demo proves that concatenating characters to strings via TStringBuilder is slightly faster, concatenating actual strings is significantly slower. In a series of test with larger strings and more real-world situations I noticed a less noticeable differnce, but it seems that string concatenation invariably wins over using the TStringBuilder. So is this new class useless? Not at all. It lets you add various data types to a string, making the code much more readable, more .NET comaptible, you can concatenate operations, and the time penatly is generally negligible. But don't use this class because it is faster... until someone rewrites it in assembly!