Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String Concatenation in VB.NET

Best Practices

String Concatenation in VB.NET

by  link9  Posted    (Edited  )
Hello all --

In ASP classic (and VB overall, for that matter), one of the most inefficient things to do was string concatenation. The reason behind this was that on every concatenation, a string variable (actually it was variant) was created and the old one was destroyed. This is because string is an immutable data type.

So that in this code bit:
Code:
dim someVar
someVar = "This "
someVar = someVar & "is old "
someVar = someVar & "string "
someVar = someVar & "concatenation."

four variables are actually created. One on each line, and then memory is reallocated for the overlying variable which is created. Poor memory management.

So has this problem been fixed in .NET? Yes and no.

If you perform your string concatenation in the same way:
Code:
Dim someString As New String()
someString &= "This "
someString &= "is old "
someString &= "string "
someString &= "concatenation."

then yes, you still suffer the same performance degradation.

However, we have been provided with a new class in .NET called the stringBuilder. And it dynamically allocates the memory block to the same object (the stringBuilder, itself, not the string)... expanding it on each concat so that you gain better performance. It resides in the system.text namespace and here's how you use it:
Code:
Imports System.Text

Dim newStringBuilder As New StringBuilder()
newStringBuilder.Append("This ")
newStringBuilder.Append("is new ")
newStringBuilder.Append("string ")
newStringBuilder.Append("concatenation.")

Dim myString As New String(newStringBuilder.toString())

So that they're really two separate objects, and the string builder takes care of memory management while you're building the string, and then you just call the .toString() method of the stringBuilder to output the result to the new string object, thereby only calling the new string() once, and avoiding the pitfalls of its inefficiencies.

And remember... Every little bit counts!

happy coding! :)
Paul Prewett

-------------------------------------
For anyone reading this FAQ before this addendum, I was misinformed when I was told that C# does not suffer from this same condition (there used to be a note here saying not to worry about it if you're using c#). Strings are immutable .NET datatypes, and therefore the condition is present in both c# and vb.net. Use stringbuilders in both languages.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top