The VB.NET sample code below can be used to demonstrate the
relative performance of string concatenation using either the traditional
method or by making use of the StringBuilder class. The code is currently
configured to perform 50,000 iterations of each concatenation technique.
Listing 5
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim OldMethodStart As New TimeSpan
Dim OldMethodEnd As New TimeSpan
Dim OldString As String = ""
Dim NewMethodStart As New TimeSpan
Dim NewMethodEnd As New TimeSpan
Dim NewString As String = ""
Dim NewStringBuilder As New System.Text.StringBuilder
'Old method of appending strings
OldMethodStart = DateTime.Now.TimeOfDay
Dim i As Integer = 0
For i = 1 To 50000
OldString = OldString & "Number " & i.ToString()
Next
OldMethodEnd = DateTime.Now.TimeOfDay
Response.Write("Old method took ")
Response.Write((OldMethodEnd.TotalMilliseconds -
OldMethodStart.TotalMilliseconds).ToString("N2"))
Response.Write(" milliseconds.")
'New method of appending strings
NewMethodStart = DateTime.Now.TimeOfDay
Dim j As Integer = 0
For j = 1 To 50000
NewStringBuilder.Append("Number " & j.ToString())
Next
NewMethodEnd = DateTime.Now.TimeOfDay
Response.Write("new method took ")
Response.Write((NewMethodEnd.TotalMilliseconds -
NewMethodStart.TotalMilliseconds).ToString("N2"))
Response.Write(" milliseconds.")
End Sub
As an example, this code was run three times using 10,000,
25,000 and 50,000 iterations. With 10,000 iterations, the traditional string
concatenation method took an average of 4831.5 milliseconds. By contrast, the
string append method took 10.4 milliseconds. The difference is exponentially greater
the more the iterations are performed. With 25,000 iterations, the traditional
string concatenation method took an average of 29,239.2 milliseconds and the
string append method took only 20.8 milliseconds. At 50,000 iterations, the
traditional method took an average of 116,899.4 milliseconds and the string
append method took 41.7 milliseconds.