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 a C# String Builder to understand the difference. Let us say

string str = "Hello";

For the above variable value, 5 bytes will allocate in heap memory. Next,

str = str + “World”;

Since the C# String Builder has been immutable, and the “World” is not concatenated with the original str value. 

Instead, another string will create in memory by appending “World” to the “Hello”.

Heap Memory

Hello
Hello World
Hello World ABC
.
.

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

C# String Builder

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

The C# String builder Syntax is shown below.

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 text, it will double the size as per the requirement.

In case we know the exact size of how much memory requires for the modifications of text, 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, “Hello” occupies 5 bytes, and StringBuilder allocates 16 bytes, where the remaining 11 bytes are for future modifications of the C# string.

Let’s say “Hello” concatenates with another “World”, i.e., 

sb.Append("World");

As you know, Hello World has a total of 11 bytes occupied, leaving 5 bytes empty.

Now some ABCDEF appends to str

str+=ABCDEF;

Hello World, ABCDEF requires 18 bytes, but only 16 bytes are available. Hence it increases the double memory 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 variable value.

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 StringBuilder class.

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

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 code demonstrated 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 initialized with “Tutorial”.

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

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

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

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

“Hello !! from Tutorial Gateway”

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

C# String Builder to find the difference

Here we are going to find out the difference in time taken for String as well as StringBuilder 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();
  }
}
C# String Builder 2

ANALYSIS

In this C# String builder example, we will take an empty s. Next, we have taken a StopWatch class and created an instance st for it. This StopWatch class is from System.Diagnostics namespace

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

We have written the C# for loop where 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().

In the same way, using it also created an instance sb for string builder for which 5000 passed as an argument, meaning sb creates an empty string with the capacity of 5000.

Before the loop begins, StopWatch created its instance, and it calls start().

Here also loop iterates 5000 times, and each time i value appends to it. After the iterations are completed, StopWatch gets stopped.

Finally, we have printed the time taken for String as well as StringBuilder separately using the property ElapsedMilliseconds of the 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.

Categories C#