Link Round-Up For 8/29/07Site News for 8/26/07 through 9/1/07

Introduction to the StringBuilder Class

August 31st, 2007

StringBuilder helps you build a program as strong as a brick wallIf you’ve been around VB a while you know that concatenating strings, particularly large strings over about 1K, can be a time consuming task for your applications. To deal with this, Microsoft introduced the StringBuilder class in the .NET Framework in the System.Text Namespace. In this article we’ll look at the advantages of using it and go over some of the fundamentals of using it.

Why Use StringBuilder?

You still see a lot of code around that uses the old string concatination methods. That’s not surprising because it’s comfortable and familiar to use for most VB’ers. But, there are two good reasons to use StringBuilder for large or looped string concatenation operations: speed and readability.

Speed is really a no-brainer. Using StringBuilder averages around 10 times faster than the concatenation operator ‘&’ or the String.ConCat function. It’s highly optimized for fast string operations. Even C++ .NET programmers have trouble outperforming it.

Readability is the other advantage. How often have you seen, or even written, code like this:

sSQL = "UPDATE Profile " & _
       "SET FName='" & txtFName.Text & "', " & _
       "MName='" & txtMName.Text & "', " & _
       "LName ='" & txtLName.Text & "', " & _
       "NickName='" & txtNickname.Text & "', " & _
       "Address='" & txtAddress.Text & "', " & _
       "Phone='" & txtPhone.Text & "', " & _
       "Email='" & txtEmail.Text & "', " & _
       "Status='" & cboStatus.Text & "', " & _
       "Notes='" & txtNotes.Text & " " & _
       "WHERE (ProfileID = " & txtProfileID.Text & ");"

or code like this

sSQL = "UPDATE Profile "
    sSQL = sSQL & "SET FName='" & txtFName.Text & "', "
    sSQL = sSQL & "MName='" & txtMName.Text & "', "
    sSQL = sSQL & "LName = '" & txtLName.Text & "', "
    sSQL = sSQL & "NickName = '" & txtNickname.Text & "', "
    sSQL = sSQL & "Address = '" & txtAddress.Text & "', "
    sSQL = sSQL & "Phone ='" & txtPhone.Text & "', "
    sSQL = sSQL & "Email='" & txtEmail.Text & "', "
    sSQL = sSQL & "Status= '" & cboStatus.Text & "', "
    sSQL = sSQL & "Notes='" & txtNotes.Text & " "
    sSQL = sSQL & "WHERE (ProfileID = " & txtProfileID.Text & ");"

This code is usually difficult to read and even more difficult to debug, especially if it goes on for 20, 30 or even 50+ lines like I’ve seen some code. It can even be difficult to code this originally since it’s quite easy to mistype something.

Append, AppendLine, and AppendFormat

We’ll begin looking at StringBuilder by taking a look at how we could build the same SQL statement above using StringBuilder and then taking a look at the Append commands. (Note that I don’t recommend building SQL statements dynamically like this due to SQL injection risks but it’s a good common string building example.)

Here’s the StringBuilder code:

Dim SqlBuilder As New System.Text.StringBuilder
With SqlBuilder
    .Append("UPDATE Profile ")
    .AppendFormat("SET FName='{0}', ", txtFName.Text)
    .AppendFormat("MName='{0}', ", txtMName.Text)
    .AppendFormat("LName='{0}', ", txtLName.Text)
    .AppendFormat("NickName='{0}', ", txtNickname.Text)
    .AppendFormat("Address='{0}', ", txtAddress.Text)
    .AppendFormat("Phone='{0}', ", txtPhone.Text)
    .AppendFormat("Email='{0}', ", txtEmail.Text)
    .AppendFormat("Status='{0}', ", cboStatus.Text)
    .AppendFormat("Notes='{0}' ", txtNotes.Text)
    .AppendFormat("WHERE (ProfileID = {0}); ", txtProfileID.Text)
End With

That’s a lot cleaner and easier to read, isn’t it? Now let’s look at the Append commands.

The Append function adds the specified value to the end of the builder. One neat thing about Append is that it not only takes a string argument but it has 19 overloads that allow you to append the major data types (Int, Long, etc.), a substring of a specified string, or the default .ToString value of an object. This makes it very powerful and easy to use as compared to standard concatenations that require type conversion (if you’re running Option Strict like you should be doing). Since it does the type conversions for you internally, this helps even more with the speed.

AppendFormat also adds the specified value to the end but also applies a format to it. In the example above, we’re using a custom format string for each line of the SQL statement that allows us to insert the value into the single quoted location without additional concatenation overhead. This method also accepts objects and does the conversion internally as part of the formatting logic.

The AppendLine adds the ‘default line terminator’, aka the CR/LF pair on all Windows systems, to the end of the builder. Optionally, you may also include a string as seen here:

With EmailBuilder
    .AppendLine()
    .AppendLine("Sincerely,")
    .AppendLine()
    .AppendLine(txtSignatureName.text)
End With

Oh, just in case you didn’t know, the standard .ToString method allows you to retrieve the internal string from StringBuilder. Also note that I like to use With blocks for it since it makes it easier to read, for me anyway.

Insert

Insert is a lot like Append in that it has overloads for most data types. However, with it, you can specify where in the character sequence the string (or string representation of an object) goes. A limitation of Insert is that unless you get the string that’s being built using the .ToString method and use the IndexOf method on the result you can’t get the position where you want to insert. This limits its usefulness a bit but it can be quick if you need to insert a hunk of text in the middle of a large string as seen in this example:

' Email built using a template
If txtPersonalMessage.Text.Length > 0 Then
    EmailBuilder.Insert(EmailBuilder.ToString.LastIndexOf("Sincerely,") - 1, txtPersonalMessage.Text)
End If

Replace

Replace, as the name implies, allows you to replace a given string with another string. This is especially powerful for templating applications when you can replace a key value in the template with a value from a database query or a business object as shown in this example:

With EmailBuilder
    .Replace("{customer_fullname}", CurrentCustomer.FullName)
    .Replace("{customer_firstname}", CurrentCustomer.FirstName)
    .Replace("{customer_city}", CurrentCustomer.City)
    'more replacements after this
End With

Remove

Remove, as you might expect, allows you to remove a specified number of characters starting at a particular position. Once again, finding the position is a little tricky. It can be useful if you need to remove a paragraph from a template, as in this example:

'we're assuming we already have the position info we need
EmailBuilder.Remove(HolidayGreetingIndex, HolidayGreeting.Length)

That wraps up the basics of using the StringBuilder class. I hope you’ve found this article helpful in learning about this class and how to use it. Let me know if you liked this article or have comments/question by leaving a comment, using the contact me button, or using the rating stars.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: VB.NET Tutorials


Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (No Ratings Yet)
Loading ... Loading ...

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives