C# String Builder

The C# String Builder is a concept that was introduced by the Dot Net framework to overcome the performance issues of datatype string. As we already know that the string is a reference type data type, i.e., memory allocated for its variable in heap memory. And string once created is immutable, i.e., it cannot be changed. However, the C# String Builder is mutable.

Let us see an example of string to understand the difference. Let us say

string str = “Hello”;

For the above string value, 5 bytes allocated in heap memory. Next,

str = str + “World”; 

Since the string is immutable, the string “World” is not concatenated with the original str value. 

Instead, another string is created in memory by appending string “World” to the “Hello”.

Heap Memory

Hello
Hello World
Hello World ABC
.
.

In this way, if we try to modify the string 100 times, 100 copies will be maintained in a heap and one for the original string. Total, it will keep 101 copies.

C# String Builder

The C# String Builder is mutable in the sense changes can be done for a string. And the StringBuilder is available form System.Text namespace.

The C# String builder Syntax:

StringBulder sb = new StringBuilder(“string str”); // It creates a stringbuilder with the specified string

For Ex:

StringBulder sb = new StringBuilder(“Hello”);

Here sb is a StringBuilder object which allocates 16 bytes at first. And while doing modifications on a string, it will double the size as per the requirement.

In case if we know the exact size of how much memory required for the modifications of string, then we can give the size as the argument for C# StringBuilder.

The Syntax of the C# String Builder is

StringBuilder sb = new StringBuilder(int length); // It creates an empty stringbuilder with the specified capacity as length

For Ex:

StringBuilder sb = new StringBuilder(1000);

For instance, string “Hello” occupies 5 bytes, StringBuilder allocates 16 bytes, where the remaining 11 bytes are for future modifications of the C# string.

Let’s say string “Hello” is concatenated with another string “World”, i.e., 

sb.Append("World");

As you know, Hello World total 11 bytes are occupied, leaving 5 bytes empty.

Now some ABCDEF is appended to str

str+=ABCDEF; 

Hello World ABCDEF requires 18 bytes, but only 16 bytes available. Hence it increases the memory double time, i.e., increases to 32 bytes.

Heap Memory

Hello World ABCDEF

The C# String Builder maintains only one copy in heap memory irrespective of the number of changes made to that string.

NOTE: If there are some three to four times, the modification has to be done, then go for String class. If there are a large number of changes to be done for a string, then go for the C# StringBuilder class.

The following methods are useful for modifying the C# String Builder string:

Method NameDescription
StringBuilder.Append()Adds data at the end of the current StringBuilder
StringBuilder.Insert()Inserts a string to the StringBuilder in the index specified.
StringBuilder.Remove()Removes the specified number of characters from the StringBuilder
StringBuilder.Replace()Replaces a specified character in the index specified
StringBuilder.AppendFormat()Format specifier passed in a string is replaced with formatted text

C# String Builder Example

Let us an example C# code demonstrating on StringBuilder.

using System.Text;

class program
{
  public static void Main()
  {
    string str = "Tutorial";
    StringBuilder sb = new StringBuilder(str);
    sb.Append(" Gateway");
    Console.WriteLine(sb);
    sb.Insert(0, "Welcome To ");
    Console.WriteLine(sb);
    sb.Replace("Welcome To", "Hello!! from");
    Console.WriteLine(sb);
    Console.ReadLine();
  }
}

OUTPUT

C# String Builder 1

ANALYSIS

In this C# String Builder example, str is a string variable which initialized with “Tutorial”.

sb is an object of type StringBuilder to which str passed as an argument.

sb.Append(“Gateway”) will append “Gateway” to string “Tutorial”

sb.Insert(0, “Welcome To”) will insert the string “Welcome To” at 0th position of the string “Tutorial Gateway”.

sb.Replace(“Welcome To”, “Hello!! From”) will replace the string “Welcome To” in “Welcome To Tutorial Gateway” with “Hello!! from” and prints

“Hello !! from Tutorial Gateway”

Let us write the C# code to know the performance of the StringBuilder class over the String class.

C# String Builder Example 2

Here we are going to find out the difference in time taken for String as well as C# String Builder in doing the same number of iterations.

using System;
using System.Text;
using System.Diagnostics;

class program
{
  public static void Main(string[] args)
  {
    string s = "";
    Stopwatch st = new Stopwatch();
    st.Start();
    for (int i = 1; i <= 5000; i++)
    {
      s = s + i;
    }
    st.Stop();
    StringBuilder sb = new StringBuilder(5000);
    Stopwatch st1 = new Stopwatch();
    st1.Start();
    for (int i=1;i<=5000;i++)
    {
      sb.Append(i);
    }
    st1.Stop();
    Console.WriteLine("Time taken for string: " + st.ElapsedMilliseconds);
    Console.WriteLine("Time taken for StringBuilder: " + st1.ElapsedMilliseconds);
    Console.ReadLine();
  }
}

OUTPUT

C# String Builder 2

ANALYSIS

Here an empty s is taken. Next, we have taken a StopWatch class and created an instance st for it. This StopWatch class is from System.Diagnostics namespace

st.Start() is to start the StopWatch before the loop gets started

The C# for loop is written in which int i initialized with 1, and i will iterate 5000 times. Each time I value concatenated with the string variable s.

st.Stop() will stop the StopWatch().

The same way using StringBuilder also created an instance sb for string builder for which 5000 passed as an argument, which means sb creates an empty string with the capacity of length 5000.

Before loop begin StopWatch created its instance and it calls start()

Here also loop is iterated 5000 times, and each time i value appended to the string. After the iterations completed, StopWatch gets stopped.

Finally, we have printed the time taken for String as well as StringBuilder separately using the property ElapsedMilliseconds of StopWatch class.

Here, finds the difference! String takes 20 milliseconds for 5000 iterations, whereas the C# String Builder takes 1 millisecond for the same number of iterations.