String Vs StringBuilder Comparison In .NET

String Vs StringBuilder Comparison Banner Image

String vs StringBuilder are similar and in most cases in .NET, we will use string but in the case of concatenation between two strings or combining strings by many times then we may need a more efficient option in StringBuilder.

Why We Use String?

Strings are very useful for a variety of circumstances. They are used for holding and displaying a variety of character types and numerical representations. A string itself is an array of char types. So a string can be indexed and can be cut up and manipulated. It can represent numbers and store those values and a combination of characters and number values.

How Strings Works

Strings are immutable reference types. This means once it is created it can’t be changed. But when we try to change the value instead of updating the string it creates a new string in its place. So when we declare a reference to a string object and give it a value and then behind the scenes a new string object is created. This is different than some other types such as an int. When we create an int variable we can change the value, C# does not create a new int variable but it changes the value of int. Below is some sample code of what I just saw about string.

    static void Main(string[] args)
    {
        string myValue = "Some Text";
        Console.WriteLine(myValue);
        myValue = "Some New Text"; // a new string object is created and replaces the previous value;// a new string object is created and replaces the previous value;
        Console.WriteLine(myValue);
    }

Output

    Some Text
    Some New Text

Motivation for StringBuilder

A drawback of the string is that it can slow down our application in cases where we are assigning and reassigning the string value many times. Because as we mentioned before each time we change a string, in the backend it is not being changed or updated but replaced by a new string object each time. This is an overhead if we are doing a lot of string manipulations. With the StringBuilder object, we can get around this overhead when we manipulate strings. StringBuilder is recommended use if we are using heavy string operations. Below is an example of the time comparisons between the two objects.

Full example solution if you are interested below.

    using System;
    using System.Diagnostics;
    using System.Text;
    namespace StringVsStringBuilder
    {
        class Program
        {
            public static int Count = 10000;
            public int MyProperty { get; set; }
            static void Main(string[] args)
            {
                GenerateRandomTextByStringBuilder();
                GenerateRandomTextByString();
            }
            private static void GenerateRandomTextByString()
            {
                string randomLetters = "abcdefghijklmnopqrstuvwxyz";
                Stopwatch stopWatch = new Stopwatch();
                Random random = new Random();
                stopWatch.Start();
                string myContent = "Some Random Text With String:";
                for (int i = 0; i < Count; i++)
                {
                    int randomIndex = random.Next(0, randomLetters.Length);
                    myContent += randomLetters[randomIndex];
                }
                stopWatch.Stop();
                Console.WriteLine(myContent);
                Console.WriteLine($"GenerateRandomTextByString:In Minutes:{stopWatch.Elapsed.Minutes}, seconds:{stopWatch.Elapsed.Seconds}, milliseconds:{stopWatch.Elapsed.Milliseconds}");
            }
            private static void GenerateRandomTextByStringBuilder()
            {
                string randomLetters = "abcdefghijklmnopqrstuvwxyz";
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
                StringBuilder myContent = new StringBuilder("Some Random Text With String:");
                Random random = new Random();
                for (int i = 0; i < Count; i++)
                {
                    int randomIndex = random.Next(0, randomLetters.Length);
                    myContent.Append(randomLetters[randomIndex]);
                }
                string finalOutput = myContent.ToString();
                stopWatch.Stop();
                Console.WriteLine(finalOutput);
                Console.WriteLine($"GenerateRandomTextByStringBuilder:In Minutes:{stopWatch.Elapsed.Minutes}, seconds:{stopWatch.Elapsed.Seconds}, milliseconds:{stopWatch.Elapsed.Milliseconds}");
            }
        }
    }

Next, we'll look at each function.

    private static void GenerateRandomTextByString()
    {
        string randomLetters = "abcdefghijklmnopqrstuvwxyz";
        Stopwatch stopWatch = new Stopwatch();
        Random random = new Random();
        stopWatch.Start(); string myContent = "Some Random Text With String:";
        for (int i = 0; i < Count; i++)
        {
            int randomIndex = random.Next(0, randomLetters.Length);
            myContent += randomLetters[randomIndex];
        }
        stopWatch.Stop();
        Console.WriteLine(myContent);
        Console.WriteLine($"GenerateRandomTextByString:Content Generated In Minutes:{stopWatch.Elapsed.Minutes}, seconds:{stopWatch.Elapsed.Seconds}, milliseconds:{stopWatch.Elapsed.Milliseconds}");
    }

Let’s note the time that it takes to complete 10000 string additions to an existing string. This addition is a concatenate operation. It is combining the previous string with another string.

Output

    Some Random Text With String:..czfizeyiozxztpxhganuvegpphisdghekgg
    GenerateRandomTextByString:In Minutes:0, seconds:0, milliseconds:10

It takes 18 milliseconds to concatenate 10000 strings together which is under a second. It seems fast but let’s see how long it takes the do the same operation with a string builder object.

    private static void GenerateRandomTextByStringBuilder()
    {
        string randomLetters = "abcdefghijklmnopqrstuvwxyz";
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start(); StringBuilder myContent = new StringBuilder("Some Random Text With String:");
        Random random = new Random();
        for (int i = 0; i < Count; i++)
        {
            int randomIndex = random.Next(0, randomLetters.Length);
            myContent.Append(randomLetters[randomIndex]);
        }
        string finalOutput = myContent.ToString();
        stopWatch.Stop();
        Console.WriteLine(finalOutput);
        Console.WriteLine($"GenerateRandomTextByStringBuilder:Content Generated In Minutes:{stopWatch.Elapsed.Minutes}, seconds:{stopWatch.Elapsed.Seconds}, milliseconds:{stopWatch.Elapsed.Milliseconds}");
    }

Output

    Some Random Text With String:...lgnveeadliwoaavtcxfblbbjrfgqqjyoiepjdogrcjxfthvdgeqrrhskfeezxk
    GenerateRandomTextByStringBuilder:In Minutes:0, seconds:0, milliseconds:1

String vs StringBuilder Test Conclusions

Wow, it takes only 1 millisecond to do this operation with a StringBuilder object. Since we are talking about differences in milliseconds this may not seem like a big deal but in large-scale applications that crunch a lot of data these kinds of optimizations are cost and time savers.

String and StringBuilder Considerations

We need to pick the right tools for the job and know when to take trade-offs when necessary. If I’m building a quick application and I’m just storing and displaying string values then a StringBuilder object isn’t necessary. But if I find myself doing a lot of string manipulation then I might consider using StringBuilder. String and StringBuilder are both useful but it depends on the context, needs, and resources that you have.

C# Programming for Unity Game Development Specialization

COURSERA

C# Programming for Unity Game Development Specialization

4.7 (2,230 reviews)

Beginner level

No previous experience is necessary

3-months at 10 hours a week (At your pace)

$59 / month or audit, and financial aid available

If you want to learn more about C# then check out this course on Coursera. It's a 3 month course to take you through the basics of C#.

You can get started with programming using C# and apply it to Unity games in this beginner-level program. Facilitated by the University of Colorado, the program offers a chance to grasp the basics of C# and utilize the knowledge to develop Unity games.

[Full Disclosure: As an affiliate, I receive compensation if you purchase through this link]

Start Your 7-day Free Trial
Get Latest Updates