Microsoft KB Archive/306821

From BetaArchive Wiki

Article ID: 306821

Article Last Modified on 12/6/2006



APPLIES TO

  • Microsoft Visual Basic .NET 2002 Standard Edition
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic 2005



This article was previously published under Q306821

For a Microsoft Visual C# .NET version of this article, see 306822.


For a Microsoft Visual Basic 6.0 version of this article, see 170964.

IN THIS TASK

SUMMARY

REFERENCES

SUMMARY

This article demonstrates the benefits of using the StringBuilder class over traditional concatenation techniques. Strings in the .NET Framework are invariant (that is, the referenced text is read-only after the initial allocation). This provides many performance benefits and poses some challenges to the developer who is accustomed to previous versions of Visual Basic. One common Visual Basic 6.0 string concatenation technique can be up to 1,000 times faster than the & operator, yet this technique provides no performance benefits in Visual Basic .NET or Visual Basic 2005.

back to the top

Description of Strings in the .NET Framework

One technique to improve string concatenation in Visual Basic 6.0 and earlier was to allocate a large string buffer and use the Mid statement to copy string data into the buffer. This technique is illustrated in the following Microsoft Knowledge Base article:

170964 How To Improve String Concatenation Performance


In the .NET Framework, a string is immutable; it cannot be modified in place, unlike strings in earlier versions of Visual Basic. Instead, any modifications to a string in the .NET Framework cause a new string to be allocated. Visual Basic .NET still includes a Mid statement, but its implementation uses concatenation to build the new string as opposed to modifying the string contents in place. As a result, the technique that is outlined in 170964 does not improve string concatenation performance in Visual Basic .NET.

The .NET Framework includes a StringBuilder class that is optimized for string concatenation. It provides the same benefits as using the Mid statement in previous versions of Visual Basic, as well as automatically growing the buffer size (if needed) and tracking the length for you. The sample application in this article demonstrates the use of the StringBuilder class and compares the performance to concatenation.

back to the top

Build and Run a Demonstration Application

  1. Start Visual Studio .NET or Visual Studio 2005, and create a new Visual Basic Console Application.
  2. The following code uses the &= concatenation operator and the StringBuilder class to time 5,000 concatenations of 30 characters each. Add this code to the Sub Main procedure.

    Const sLen = 30, Loops = 5000
    Dim sTime, eTime As DateTime, I As Integer
    Dim sSource As New String("X"c, sLen)
    Dim sDest As String = ""
    '
    ' Time string concatenation
    '
    sTime = Now
    For I = 1 To Loops
        sDest &= sSource
    Next I
    eTime = Now
    Console.WriteLine("Concatenation took " & eTime.Subtract(sTime).TotalSeconds & " seconds.")
    '
    ' Time StringBuilder
    '
    sTime = Now
    ' Initialize the StringBuilder buffer slightly larger
    ' than what you expect to need.
    Dim sb As New Text.StringBuilder(CInt(sLen * Loops * 1.1))
    For I = 1 To Loops
        sb.Append(sSource)
    Next I
    sDest = sb.ToString()
    eTime = Now
    Console.WriteLine("String Builder took " & eTime.Subtract(sTime).TotalSeconds & " seconds.")
    '
    ' Make the console window stay open so that you can
    ' see the results when you are running from the IDE.
    '
    Console.WriteLine()
    Console.Write("Press ENTER to finish ... ")
    Console.Read()
                        
  3. Save the application, and press the F5 key to compile and run the application. The console windows should display output similar to the following:
    Concatenation took 6.208928 seconds.
    String Builder took 0 seconds.
    
    Press ENTER to finish ...
                            
  4. Press ENTER to stop running the application and close the Console window.

back to the top

Troubleshooting

  • If you are in an environment that supports streaming the data, such as in an ASPX Web Form or your application is writing the data to disk, consider avoiding the buffer overhead of concatenation or the StringBuilder, and write the data directly to the stream through the Response.Write method or the appropriate method for the stream in question.
  • Try to reuse the existing StringBuilder class rather than reallocate each time you need one. This limits the growth of the heap and reduces garbage collection. In either case, using the StringBuilder class makes more efficient use of the heap than using the & operator.

back to the top

REFERENCES

The StringBuilder class contains many other methods for in-place string manipulation that are not described in this article. For more information, search for "StringBuilder" in the Online Help.

back to the top

Keywords: kbvs2005swept kbvs2005applies kbhowtomaster KB306821