Technology Microsoft Software & solutions

StringBuilder ... A New Object in .NET

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

Related posts "Technology : Microsoft Software & solutions"

How to Import OCX

Microsoft

How to Install Grub From a Fedora Recovery CD

Microsoft

How to Speed Up Streaming in Vista

Microsoft

How to Fix a Disappearing "Start" Menu, "Start" Button and Task Bar

Microsoft

How Do I Modify Startup in Vista?

Microsoft

How to Change Your Name in CP

Microsoft

How to Use WinImage to Create a Boot Disk ISO

Microsoft

How to Get to a BIOS Screen

Microsoft

How to Control Updates on XP

Microsoft

Leave a Comment