Porting a Delphi for NET Example

As a test of the source code compatibility of Delphi's TStringBuilder class with .NET's StringBuilder class, I've taken another example that I had written in Delphi for .NET for the "Mastering Delphi 2005" book and converted it to a VCL application.

The program had two radio buttons to pick a string of different size, a list box for the output, and two buttons to process the strings with either a TStringBuilder or a plain string. Simply by defining a type alias for TStringBuilder called StringBuilder, the core of the method compiles without a single change: /// actual code strB := StringBuilder.Create; if rbShort.Checked then strB.Append (strSampleShort) el se strB.Append (strSampleLong);

for I := l to maxCount do begi n nPos := I mod strB.Length; strB.Remove(nPos, l);

strB.Insert(nPos, strB [(I*2) mod strB.Length]); end;

107 For more ideas on this issue, see also my blog post "Not so fast, TStringBuilder" at: http: //blog.marcocantu.com/blog/not_so_fast_tstringbuilder.html.

ListBox1.Items.Add (strB.ToString); /// end of actual code

All I had to do was to remember to add a call to Free, as we are not on a reference counted platform like .NET. The string processing code, instead, is totally different between Delphi Win32 and the .NET FCL version, so I had to rewrite it entirely. What is interesting to notice is that in this code which keeps removing and inserting data in the string, the TStringBuilder-based code is noticeably faster:

btnSBuilderClick: 00.112 btnStringClick: 00.246

Unlike in .NET (where strings are immutable and direct string operations are terribly slow) using a shorter or longer string makes almost no difference, but I've left the radio buttons and the related string constants in the code to keep it as close as possible to the original.

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment