stringbuilder

StringBuilder vs String Concatenation

This blog will show you String Concatenation and .NET’s StringBuilder Class. The differences between the two and in what situation one is more appropriate than the other.

String Concatenation in .NET

String Concatenation in simple terms is adding 2 or more strings together to form one string.  This is the simplest form of string manipulation.

Example:

namespace StringBuilderExample

{
    class Program
    {
        static void Main(string[] args)
        {
            Concatenation();
        }       

        private static void Concatenation()
        { 
            var firstString = "Hello";
            var secondString = "World";

            var concatenatedString = firstString + secondString;

            Console.WriteLine("The First String: " + firstString);
            Console.WriteLine("The Second String: " + secondString);
            Console.WriteLine("The Concatenated String: " + concatenatedString);
            Console.ReadLine();
        }
    }
}

ConcatResult

It’s pretty straightforward right?

.NET StringBuilder

StringBuilder is a string of Mutable characters.  Mutable means that it can be changed once the Type’s instance has been created.  This is a very good reason to use StringBuilder and I will explain why in a bit with a test.

namespace StringBuilderExample
{
    class Program
    {
        private static string[] wordListArray = { "I", "am", "joining", "multiple", "strings", "together", "multiple", "times!!" };
        
        static void Main(string[] args)
        {                        
            StringBuilder();
        }
 
        private static void StringBuilder()
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("I am using");
 
            Console.WriteLine(stringBuilder.ToString());
 
            stringBuilder.AppendLine("the StringBuilder class");
 
            Console.WriteLine(stringBuilder.ToString());
 
            stringBuilder.AppendFormat("to {0} the {1} together!", "append", "strings");
 
            Console.WriteLine(stringBuilder.ToString());
            Console.ReadLine();
        }
    }
}

StringBuilderExample1

StringBuilder vs String Concatenation

Now, which one has better performance?  Using the StringBuilder Class seems like a lot more work to use and it can be but it was created for a reason.  Strings by themselves areImmutable, meaning that once that Type is instantiated its data, properties, and fields cannot be changed.  So anytime a string concatenation occurs a new string is created with the two joined.

This is where the pitfall of appending strings together comes in.  StringBuilder doesn’t have this problem, when you append to the stringbuilder instance, it appends to the already existing instance.

Here is an example of StringBuilder vs. String Concatenation

namespace StringBuilderExample
{
    class Program
    {
        private static string[] wordListArray = { "I", "am", "joining", "multiple", "strings", "together", "multiple", "times!!" };
        
        static void Main(string[] args)
        {                        
            StringBuilderVsConcatenation();
        }
 
        private static void StringBuilderVsConcatenation()
        {
            var stopWatch = new Stopwatch();
            var stopWatch2 = new Stopwatch();
 
            var stringBuilder = new StringBuilder();
            var concatenatedString = string.Empty;
 
            stopWatch.Start();
 
            for (int x = 0; x <= 10000; x++)
            {
                for (int i = 0; i < wordListArray.Length; i++)
                {
                    if (i == wordListArray.Length)
                        stringBuilder.AppendLine();
 
                    stringBuilder.AppendFormat("{0} ", wordListArray[i]);
                }
                stringBuilder.AppendLine();
            }
 
            stopWatch.Stop();
 
            stopWatch2.Start();
 
            for (int y = 0; y <= 10000; y++)
            {
                for (int i = 0; i < wordListArray.Length; i++)
                {
                    if (i == wordListArray.Length)
                        concatenatedString += ""; 

                    concatenatedString += wordListArray[i] + " ";
                }
                concatenatedString += "";
            }
 
            stopWatch2.Stop();
 
            Console.WriteLine("StringBuilder:{0} seconds ", stopWatch.Elapsed.TotalSeconds.ToString());
            Console.WriteLine("Appending:{0} seconds", stopWatch2.Elapsed.TotalSeconds.ToString());

            Console.ReadKey();
        }
    }
}

stringVsBuilder

StringBuilder is almost 14 seconds faster than doing simple concatenation. Now this doesn’t seem like a big deal, but imagine working with a large system that uses something like a Date-Range reporting system.

Let’s say a company wanted to know how many items it shipped in the last month. Using the StringBuilder Class could be the difference between minutes to hours depending on the amount of information.

So if your program is going to incorporate heavy string manipulation, using the StringBuilder class will save you a serious amount of processing time. If not, simple string concatenation might be just what the doctor ordered. It all depends on what you’re doing, so choose wisely.

You may also like

Leave a comment