Fast and Efficient C# and Visual Basic String Concatenation

If you do any sort of web development work on the .NET platform, you are going to find yourself concatenating (connecting) strings together on a very regular basis. There are two ways to do this.

The first is with a traditional string concatenation, which would look something like this:

string MyString = String.Empty;
MyString = “Hello ” + “World”;

The second way, is using the StringBuilder library, which would look something like this:

StringBuilder MyString = new StringBuilder();
MyString.Append(“Hello “);

These two sets of code do basically the same thing, but is it preferable to use one over the other? It turns out, that the StringBuilder class is much, much more efficient when dealing with large sets of strings. For short strings, with fewer than five concatenations, chances are you’ll be better off with traditional string concatenation because you don’t have to instantiate a copy of the StringBuilder library, but for situations that you want to do a lot of string manipulation, you definitely want to use the StringBuilder library.

Here’s a synthetic test using C# and ASP.NET comparing the two:

        Trace.IsEnabled = true;

        StringBuilder StBuilder = new StringBuilder();
        Trace.Write(“String Builder Append Begin”);
        for (int x = 0; x < 10000; x++)
        Trace.Write(“String Builder Complete”);

        string stString = String.Empty;
        Trace.Write(“String Concatenation Beginning”);
        for (int x = 0; x < 10000; x++)
            stString += “Testing123”;
        Trace.Write(“String Concatenation Complete”);

The test concatenated the string 10,000 times. Although it’s a synthetic test, it shows that the StringBuilder class is substantially more efficient than the string class for concatenation. The string class concatenated the text in 5.292587 seconds. The StringBuilder class performed the same task in just 0.006142 seconds. In other words, the StringBuilder was over 850 times faster at concatenating the string than the string class was.

Now that’s a performance benefit!


  1. Thank you for very useful information. It is interesting to know that there are outsourcing software engineering companies that helps in software development.

Speak Your Mind