Parag’s Den

Dedicated to my adored friends…..

Asp.Net (Always use StringBuilder for String Concatenations)

Posted by paragdongre on November 6, 2007

In ASP.NET, we have a new object called StringBuilder.

Many people have asked why we need to have a stringBuilder, since it is very easy to concatinate strings.

Of Course it is very easy to concatinate strings with the operators plus and ampersand. But the disadvantages of using these operators are:

a) for every string concatination, lots of memory operation are carried out.
b) when you say
str = str + “how about this line”

First, the CPU will create a temporary memory address (let us say m1) and store the contents of str. Then the CPU will add the string, “how about this line” to the memory location m1. Finally we need to update the location of str. So, the contents of m1 will be copied to the original location of str. So, this internal process is a very time consuming one.

But the StringBuilder object uses the concept of pointers. So each time when we append a string, to an existing string, we are directly adding the contents to the existing string without allocating any memory locations.

Here is how we can make use of the StringBuilder Object.

Note:You should import the namespace System.Text to work with StringBuilder

Dim strSql as New StringBuilder

If strType = “TOFORWARD” Then
     strSql.Append (“Exec s_delete_forward ‘”)
ElseIf strType = “TOREWRITE”
     strSql.Append (“Exec s_delete_rewrite ‘”)
End If

strSql.Append (strSource)
strSql.Append (“‘, ‘”)
strSql.Append (strDestination)
strSql.Append (“‘”)

Response.Write (“The string is: ” & strSql.ToString())


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: