Boosting the Performance of an ASP.NET Application Using StringBuilder Class
page 5 of 7
by Brett Burridge
Feedback
Average Rating: 
Views (Total / Last 10 Days): 29425/ 56

A demonstration of string concatenation performance

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.


View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-25 8:41:38 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search