# Recipe 5.27. Speeding Up String Manipulation

#### Problem

You want to see a timing-test-based example that shows just how much faster a StringBuilder can be than standard string concatenation.

#### Solution

Sample code folder: Chapter 05\StringTime

Create a short routine to concatenate the string values of the numbers 1 to 10,000, first using direct concatenation to a string variable and then using a StringBuilder. Use Date variables to calculate elapsed time for each loop in milliseconds, and dis-play the results of each for comparison.

#### Discussion

Here's the code for doing the timing test. The two contestants are ready for the race. content is a conventional immutable string, and result is the highly acclaimed StringBuilder challenger:

` Dim content As String = "" Dim result As New System.Text.StringBuilder `

The supporting cast of characters is ready to rally to the cause. Here, counter is a loop counter, dateTime1 tHRough dateTime3 are Date variables to hold instants in time, and loopCount provides the number of laps for the race:

` Dim counter As Integer Dim dateTime1 As Date Dim dateTime2 As Date Dim dateTime3 As Date Dim loopCount As Integer = 15000 `

The flag is waved to start the race, and the starting time is noted very accurately:

` Me.Cursor = Cursors.WaitCursor dateTime1 = Now `

The first contestant runs all the loops, concatenating the string representations of the numbers for each lap into one big string named content. The time of completion is carefully noted:

` For counter = 1 To loopCount    content &= counter.ToString() Next counter dateTime2 = Now `

The StringBuilder now runs the same laps, appending the same strings in its internal buffer. The time at completion is accurately noted:

` For counter = 1 To loopCount    result.Append(counter.ToString()) Next counter dateTime3 = Now `

The flag drops, signaling the crossing of the finish line for both contestants:

` Me.Cursor = Cursors.Default `

In a moment, the results of the race appear:

` content = String.Format( _    "First loop took {0:G4} ms, the second took {1:G4} ms.", _    dateTime2.Subtract(dateTime1).TotalMilliseconds, _    dateTime3.Subtract(dateTime2).TotalMilliseconds) MsgBox(content) `

The results are shown in the message box displayed in Figure 5-30. Due to differences between systems, your results may vary.

##### Figure 5-30. The StringBuilder is the clear winner of this race

To be fair, this race was highly contrived to help point out the difference in operational speed between string concatenation and StringBuilder appending. If you create a loop in which the same strings are used each time, the timing is much more equal. This is because Visual Basic handles immutable strings very intelligently, reusing existing strings whenever possible and hence speeding up repetitive operations involving the same data. The test shown here creates a unique string for each concatenation by converting the loop index number to a string, forcing a lot of extra string creation and storage in memory during the loops.

When running this test yourself, you might need to adjust the value of loopCount for your system. If the race seems to take too long, stop the program manually and adjust loopCount to a value a few thousand lower; if the race is too fast, resulting in an apparent elapsed time of 0ms for the StringBuilder, bump up loopCount by a few thousand, and try again.

Recipe 5.1 and Recipe 5.26 provide additional discussion of strings and StringBuilder instances.

Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon