C# String VS StringBuilder | Top 5 Differences between string and StringBuilder

C# string vs stringbuilder
C# String VS StringBuilder

The string is an immutable type in C#, which means it can’t be changed once it’s been created. StringBuilder, on the other hand, is mutable, which means that if an operation is performed on the string object, it won’t construct a new instance in memory every time, unlike string.

Difference between string and StringBuilder in C#

The differences between the string and StringBuilder are listed below.

C# String C# StringBuilder
1. The string class is available in System Namespace. The StringBuilder class is available in System.Text Namespace
2. A string instance is immutable (unchangeable). String objects once created cannot be changed. A StringBuilder class is mutable (changeable), which means if we create a string builder instance then we can perform any operation on it.
3. If we perform any operation on a String instance, it will create a new instance in the heap memory instead of modifying the existing string value.
Example:
string stringValue = “Hello “;
// creating a new string instance instead of modifying the old one.
stringValue += “World”;
If we perform any operation on a StringBuilder instance, it will update the existing instance value rather than creating a new one in the memory.
Example:
StringBuilder sb = new StringBuilder();
sb.Append(“Hello “);
sb.Append(“World”);
string stringValue = sb.ToString();
4. Because String is immutable, it can be used across multiple threads without causing synchronization issues. Thread safety is ensured.The StringBuilder in C# is not thread-safe since it lacks synchronization.
5. Performance degrades when heavy string manipulations or concatenation are involved.StringBuilder is mutable, So it provides better performance as compared to the String object because the new changes are made to an existing instance instead of creating the new one in the memory.
C# String vs StringBuilder Comparision

String in C#

In C#,  String   is a keyword that is used to hold the text value. It is an object of  System.String  type.

The string is immutable (unchangeable), the value once assigned to a String object cannot be modified after its creation.

If we try to change the value of the String object, it will create a new instance in a different memory location with the modified value.
In C#, a string is a series of characters that is used to represent text.

String memory allocation

Following is the pictorial representation of memory allocation for the string.

String memory allocation in heap
String memory allocation in the heap memory

Example of string concatenation

using System;
class Program
{
    static void Main(string[] args)
    {
        string str = "Hello ";

              str += "Shekh";

        // Here Concatenation (+=) actually creating a new
        // string object and releasing the
        // reference to the original object.

        Console.WriteLine(str);
        Console.ReadLine();
    }
}
// Output: Hello Shekh

The += operator creates a new string object that contains the combined contents. The previous objects get released for the garbage collection.

String concatenation can be done in two ways, either by using + = operator or by using the  String.Concat method.

string str = "Hello ";

str = String.Concat(str, "Shekh");

String interning in C#

In C#, sometimes we write a program with multiple instances of the same string.
The CLR (Common Language Runtime) stores single references to all unique strings in a special table known as Intern Pool.

    • At compilation time all the unique strings are allocated in the heap memory.
    • Only the reference is returned from the “Intern Pool” to the new string variables having the same value.

The following is the pictorial representation of memory allocation for the unique strings.

String interning in C#
String interning in C#

The following is the Sample example code :

using System;
class Program
{
    static void Main(string[] args)
    {
        string x = "SameString";

        string y = "SameString";

        string z = "DifferentString";

        Console.WriteLine("x == y {0}", Object.ReferenceEquals(x, y));
        Console.WriteLine("y == z {0}", Object.ReferenceEquals(y, z));

        Console.ReadLine();
    }
}

Unique String Output
The output of the above C# program.

In the above example, x and y variables have the same reference.

    • In C# Strings are immutable.
    • Every time we concatenate a string, a new object is created in the heap memory.
    • In C# the previous objects which are no longer used are garbage collected.
    • Modifying the same string multiple times will hinder the performance.
    • In C# use StringBuilder if the string is modifying frequently.

StringBuilder in C#

In C# we use String and StringBuilder to hold text. The only difference is, the String is immutable and StringBuilder is mutable.

The  StringBuilder  is  a dynamic object which belongs to the  System.Text  namespace.  It doesn’t create a new object in the heap memory every time we concatenate a new string.

    • In C# the StringBuilder is the better option for concatenating multiple strings together in a loop.
    • The string is efficient if we are only concatenating two or three strings.

StringBuilder memory allocation

Pictorial representation of memory allocation for the unique strings.

StringBuilder memory allocation
Memory allocation for the StringBuilder in the Heap

The following is the sample example code of using StringBuilder in C#.

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();
                      sb.Append("Hello ");
                      sb.Append("World");

        Console.WriteLine(sb);
        Console.ReadLine();
    }
}
// Output: Hello World

Declaration and Initialization of StringBuilder in C#

In C# the declaration and initialization of the StringBuilder are the same as class.

StringBuilder sb = new StringBuilder();
//or
StringBuilder sb = new StringBuilder(“Hello World”);

In the above code, ‘sb’ is the object of the StringBuilder class.
In C# we can create a new instance of the StringBuilder class by passing the value in the constructor

Setting the capacity and length of the StringBuilder

In C# StringBuilder allows us to set the maximum number of characters it can hold. After the maximum capacity is reached, a new space for the StringBuilder is allocated in the heap.

StringBuilder sb = new StringBuilder();
sb.Capacity = 10;
//or
StringBuilder sb = new StringBuilder(10);

//or
StringBuilder sb = new StringBuilder(“Hello World”, 10);

StringBuilder Methods

Method Name Description
StringBuilder.Append Appends the given information to the end of the current StringBuilder.
StringBuilder.AppendFormat Replaces a format specifier passed in a string with formatted text.
StringBuilder.InsertInserts a string or object into the specified index of the current StringBuilder.
StringBuilder.RemoveIt removes/deletes a specified number of characters from the current StringBuilder.
StringBuilder.ReplaceReplaces a specified character at a specified index of the current StringBuilder.

C# StringBuilder Append/AppendLine Method

In C# we use the  Append  method to add a new text or string at the end of the string represented by the StringBuilder. The  AppendLine 
method appends the string with a newline at the end of the string.

The following are the sample code example:

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("Hello ");

        sb.AppendLine("World");

        //Text append with a new line
        sb.AppendLine("This is a new Line");

        Console.WriteLine(sb);
        Console.ReadLine();
    }
}

/* Output:
Hello World
This is a new Line
*/

StringBuilder AppendFormat Method

In C# we can use the  AppendFormat  method to format the input string into a specified format. which can append at the end of the string represented by the StringBuilder.

In the below example we are using the AppendFormat method to place an integer value formatted as a currency ($) value.

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Total amount: ");

        int amount = 250;    

        sb.AppendFormat($"{amount:C} ");

        Console.WriteLine(sb);

        Console.ReadLine();
    }
}
// The example displays the following output:
// Total amount:  $250.00

C# StringBuilder Insert Method

In C# the  Insert  method adds a string or an object to a specified position in the StringBuilder object.
Here we are inserting a word into the sixth position of a StringBuilder object.

The following are the sample code example.

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Hello Shekh");
        sb.Insert(6," Mr. ");
        Console.WriteLine(sb);
        Console.ReadLine();
    }
}
// The example displays the following output:
// Hello  Mr. Shekh

StringBuilder Remove Method

In C# the  Remove   method of StringBuilder removes the string at the specified index with a specified length.

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Hello Shekh");
        sb.Remove(5,6);
        Console.WriteLine(sb);
        Console.ReadLine();
    }
}
// The example displays the following output:
// Hello

StringBuilder Replace Method

In C# the  Replace   method  of the StringBuilder replaces all occurrences of a specified string within the StringBuilder object by a specified replacement string.

Example:

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Hello Shekh ?");

        sb.Replace("?","!");
        Console.WriteLine(sb);

        Console.ReadLine();
    }
}
// The example displays the following output:
// Hello Shekh !

Use of Indexer in StringBuilderStringBuilder as Indexer

In C# we can use the indexer with StringBuilder to get or set characters at the specified index.
In the below example we are getting all the characters from the StringBuilder using for loop.

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Hello Shekh");

        for(int index=0; index <sb.Length; index ++)
        {
            Console.Write(sb[index]);
        }

        Console.ReadLine();
    }
}
// The example displays the following output:
// Hello Shekh

Convert StringBuilder to String

In C# we can convert a StringBuilder object to a string by using the below two methods.

    • StringBuilder.ToString()
    • Convert.ToString(StringBuilder)

Program to convert a StringBuilder object to a string.

using System;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("Hello ");

        sb.Append("Shekh");

        //Convert StringBuilder to string
        Console.WriteLine(Convert.ToString(sb));
        //or
       // Console.WriteLine(sb.ToString());
        
        Console.ReadLine();
    }
}
// The example displays the following output:
// Hello Shekh

Refrences: MSDN- StringBuilder in C#

Summary:

In this article, we talked about the difference between String and StringBuilder with various examples.

I hope you enjoyed this post and found it useful. If you have any doubt, please feel free to post your questions or suggestion in the comment section.

Recommended Articles

2 Replies to “C# String VS StringBuilder | Top 5 Differences between string and StringBuilder”

  1. Sir,
    If suppose I Concat string 10 times.
    10 objects will be created in memory.
    The 10th object will be used and the remaining ones will be in the memory.
    What will GC do of 9 objects??
    Will it remove all the 9 objects?
    If all 9 objects are removed by GC then why use String Builder?

    1. Hello, Jaydeep. There are no precise times when the garbage collector is triggered, thus if you produce ten string objects, you never know when the remaining nine string objects will be disposed of from memory by the garbage collector.
      The garbage collector searches for objects that are no longer in use and frees up memory, but you never know when it will be invoked. Any objects still in use will survive and promote to the next generation.

Leave a Reply