How to improve string concatenation performance in Visual C#

Article translations Article translations
Article ID: 306822 - View products that this article applies to.
This article was previously published under Q306822
Expand all | Collapse all

On This Page

SUMMARY

This step-by-step article shows you 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 C/C++ string manipulation techniques.

Description of Strings in the .NET Framework

One technique to improve string concatenation over strcat() in Visual C/C++ is to allocate a large character array as a buffer and copy string data into the buffer. In the .NET Framework, a string is immutable; it cannot be modified in place. The C# + concatenation operator builds a new string and causes reduced performance when it concatenates large amounts of text.

However, the .NET Framework includes a StringBuilder class that is optimized for string concatenation. It provides the same benefits as using a character array in C/C++, 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.

Build and Run a Demonstration Application

  1. Start Visual Studio, and then create a new Visual C# 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 main procedure.
    const int sLen=30, Loops=5000;
    DateTime sTime, eTime;
    int i;
    string sSource = new String('X', sLen);
    string sDest = "";
    // 
    // Time string concatenation.
    // 
    sTime = DateTime.Now;
    for(i=0;i<Loops;i++) sDest += sSource;
    eTime = DateTime.Now;
    Console.WriteLine("Concatenation took " + (eTime - sTime).TotalSeconds + " seconds.");
    // 
    // Time StringBuilder.
    // 
    sTime = DateTime.Now;
    System.Text.StringBuilder sb = new System.Text.StringBuilder((int)(sLen * Loops * 1.1));
    for(i=0;i<Loops;i++) sb.Append(sSource);
    sDest = sb.ToString();
    eTime = DateTime.Now;
    Console.WriteLine("String Builder took " + (eTime - sTime).TotalSeconds + " seconds.");
    // 
    // Make the console window stay open
    // so that you can see the results when running from the IDE.
    // 
    Console.WriteLine();
    Console.Write("Press Enter to finish ... ");
    Console.Read();
    					
  3. Save the application. Press F5 to compile and then 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 to close the Console window.

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.

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.

Properties

Article ID: 306822 - Last Review: July 14, 2008 - Revision: 3.0
APPLIES TO
  • Microsoft Visual C# 2005
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual C# 2008 Express Edition
Keywords: 
kbsweptvs2008 kbhowtomaster kbperformance KB306822

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com