1. Home
  2. Computing & Technology
  3. Visual Basic

StringBuilder ... A New Object in .NET
How Much Faster Is StringBuilder?

By Dan Mabbutt, About.com

Oct 27 2007

But just how much more efficient is StringBuilder? To find out, I coded a simple Windows Application that gives you the choice of using either. The code is below. (If you want to code this program yourself, simply create the form with the components shown in the illustration.

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

As you can see, StringBuilder was 11525 percent (that is, 115 times) faster than using String concatenation. That's a difference worth coding for!

Here's the code! The System.Diagnostics namespace was imported for the StopWatch object.

Imports System.Diagnostics
Public Class Form1
   Dim AndTimeSpan As Integer
   Dim AppendTimeSpan As Integer
   Private Sub TimeEm_Click( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArgs) _
      Handles TimeEm.Click
      If UseAnd.Checked Then UseAndTest()
      If UseAppend.Checked Then UseAppendTest()
      CalcImprovement()
   End Sub
   Private Sub UseAndTest()
      Dim myStopwatch As Stopwatch = New Stopwatch
      Dim i As Integer
      Dim LoopLimit As Integer = CInt(NumberOfIterations.Text)
      Dim TestString As String = ""
      Dim myTimeSpan As New TimeSpan
      myStopwatch.Reset()
      myStopwatch.Start()
      For i = 1 To LoopLimit
         TestString &= "B"
      Next
      myStopwatch.Stop()
      myTimeSpan = myStopwatch.Elapsed
      AndTimeSpan = myTimeSpan.Milliseconds
      UsingAnd.Text = myTimeSpan.ToString
   End Sub
   Private Sub UseAppendTest()
      Dim myStopwatch As Stopwatch = New Stopwatch
      Dim i As Integer
      Dim LoopLimit As Integer = _
         CInt(NumberOfIterations.Text)
      Dim TestAppend As New System.Text.StringBuilder
      Dim myTimeSpan As New TimeSpan
      myStopwatch.Reset()
      myStopwatch.Start()
      For i = 1 To LoopLimit
         TestAppend.Append("B")
      Next
      myStopwatch.Stop()
      myTimeSpan = myStopwatch.Elapsed
      AppendTimeSpan = myTimeSpan.Milliseconds
      UsingAppend.Text = myTimeSpan.ToString
   End Sub
   Private Sub CalcImprovement()
      Try
         PercentageImprovement.Text = _
            CStr((AndTimeSpan / AppendTimeSpan) * 100)
      Catch ex As Exception
         PercentageImprovement.Text = ""
      End Try
   End Sub
End Class

Explore Visual Basic
By Category
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Visual Basic

©2009 About.com, a part of The New York Times Company.

All rights reserved.