Introduction
This article describes a set of tips and tricks for using strings in VB.NET that will boost the performance of your applications, especially when the code contains lots of string related operations such as string concatenation. The original source of this article is taken from The home of all .NET developers - String Optimization in VB.NET. I recommend that you read those useful articles related to the .NET framework, especially the ones that are concerned with optimization, before you go on with this article.
String Declaration
The best way to declare a string variable is to set it to an empty string directly after declaration. It is a common mistake for most .NET developers to set a string to "" or Nothing. This is wrong because "" is not really an empty string for .NET CLR, and Nothing could throw a NullReferenceException if you reference the string later in the code. Below is the correct code for string declaration:
Dim str As String = "" Dim str2 As String = Nothing Dim str3 As String = vbNullString Dim str4 As String = String.Empty
String Concatenation
The usual way to concatenate strings is to use the + or the & operators. However, & is faster than + because it is specially designed for strings while + also works for numeric addition.
Dim str As String = String.Empty
str = "Hello " & " world!" & vbCrLf
For i As Integer = 0 To 4
str &= str & vbCrLf
Next
Optimizing String Concatenation
A similar class to String is called StringBuilder, located in System.Text.StringBuilder. StringBuilder is specially designed for extreme boosting of string concatenation. It is handled in a special way by the .NET CLR. It's easy to use and manipulate just like the String class. If you know how much the string length will approximately be at the end of the concatenation, you can set this capacity in the constructor of the StringBuilder, which gives an additional performance boost:
Dim str As String = "Hello World" & vbCrLf
Dim sb As New System.Text.StringBuilder(str.Length * 4)
For i As Integer = 0 To 4
sb.Append(str)
Next
Dim final As String = sb.ToString
StringBuilder also supports formatting strings using the AppendFormat method, which is highly optimized and easy to use:
Dim names As New StringCollection
names.Add("Mike")
names.Add("Stacy")
names.Add("Bill")
names.Add("Krystelle")
Dim sb As New System.Text.StringBuilder
For Each name As String In names
sb.AppendFormat("My name is {0}", name)
Next
Dim final As String = sb.ToString
There is no need to instantiate multiple StringBuilders within the same procedure. You can reuse the same StringBuilder object by setting the Capacity property to 0,which deletes the current string:
Dim sb As New System.Text.StringBuilder
sb.Capacity = 0