Using StringBuilder for string concatenation

While researching up about general good C# development fundamentals, I found some information regarding string concatenation.

Often my interaction with strings were mainly defining a message using String.Format().

e.g.

String.Format("Error {0}: {1}", errorCode, errorDescription);

But, there have been times where you might do a bit of

string str += moreString

without really thinking of the memory implications.
When you concatenate strings like this, a new copy is created each time.

Enter StringBuilder
StringBuilder will maintain the same place in memory for that string instance.
This is a far better usage of memory.

I found a great post on dotnetpearls demonstrating this memory difference.

This post provides the following code example

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

class Program
{
    static StringBuilder _builder;
    static List<string> _list;

    static void Main()
    {
        //
        // Get start memory.
        //
        long bytes1 = GC.GetTotalMemory(true);
        //
        // Allocate a list or StringBuilder of many strings.
        // ... Comment out one of these lines to one method.
        //
        //_list = GetList();
        _builder = GetBuilder();
        //
        // Compute memory usage.
        //
        long bytes2 = GC.GetTotalMemory(true);
        Console.WriteLine(bytes2 - bytes1);

        Console.ReadKey();
    }

    static List<string> GetList() // Allocate list of strings
    {
        List<string> list = new List<string>();
        for (int i = 0; i < 100000; i++)
        {
            string value = Path.GetRandomFileName();
            list.Add(value);
        }
        return list;
    }

    static StringBuilder GetBuilder() // Allocate StringBuilder of strings
    {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 100000; i++)
        {
            string value = Path.GetRandomFileName();
            builder.Append(value);
        }
        return builder;
    }
}

This example will give you the opportunity to experience the difference StringBuilder can make.

For me, I found that the List object was stored using 4524496 bytes whereas the StringBuilder object was stored using 2406896 bytes.
That’s a significant difference. Dang.

Subscribe

0 comments