Difference between String and StringBuilder in C#

Difference between String and StringBuilder in C#

In this article, we will discuss the key difference between String and StringBuilder. Since most beginners in C# get confused about their differences, I will address them in the article and at the end of this article you will have a better understanding of the difference between String and StringBuilder.

The String class and StringBuilder class represent sequences of characters that represent text values. First of all, the String class is located in the System namespace, whereas the StringBuilder class is located in the System.Text namespace.

String vs StringBuilder Comparison Table

The table below shows the differences between String vs StringBuilder:

String

StringBuilder

The String class is available in System Namespace

The StringBuilder class is available in the System.Text Namespace.

A String instance is immutable (unchangeable). String objects once created cannot be changed.

A StringBuilder is mutable (changeable), which means if we create a string builder instance then we can perform any operations on it.

Requires more memory to create a new instance if operations performed on a string change its value.

It requires less memory as it updates the exisiting instance.

Performance degrades when heavy strings manipulation or concatenations are involved.

Since StringBuilder is mutable, it provides better performance.

String class is less efficient as compared to StringBuilder while working with a large number of string concatenations.

StringBuilder is more efficient as compared to String while working with a large number of string concatenations.

An object of String is read-only in nature.

An object of StringBuilder is dynamic in nature.

Strings in C#

A string is a keyword that holds a text value. In C#, a string is a sequence of characters that represents a text. A string is immutable (unchangeable), Once the string object is created, its value cannot be changed. If we try to change the value of the string object, a new instance will be created and allocated in the memory with its modified value.

String memory allocation

Following is the pictorial representation of the memory allocation of string:

String memory allocation in the heap memory

Example of string concatenation:

using System;

class Program
{
      static void Main(string[] args)
      {
           string str = “Hello ”;
                  str += “world”;
       // Here concatenation (+=) actually creating a new string object and           releasing the reference to the original object
           Console.WriteLine(str);
           Console.ReadLine();                 
      }
}
// Output: Hello world

In the code above, the "+=" operator creates a new string object in the memory with the combined objects.

String concatenation can be done in two ways; either by using the "+=" operator or the String.Concat() method.

String name = “John ”;
String.Concat(name, “Doe”);

StringBuilder in C#

In C#, we can also use StringBuilder to hold text. The StringBuilder is a dynamic object that belongs to the System.Text namespace. It does not create a new object in the heap memory every time we modify its value.

StringBuilder memory allocation

Following is the pictorial representation of the memory allocation of StringBuilder:

Memory allocation for the StringBuilder in the Heap Memory.

The following is a sample code of using the 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

Setting the capacity of the StringBuilder

The capacity of StringBuilder is the maximum number of characters that can be contained in the memory allocated by the current instance. The default capacity of the StringBuilder class is 16 characters. To set the capacity, you need to pass a length value in the StringBuilder method:

StringBuilder sb = new StringBuilder(20);

In the above code, the StringBuilder class will accommodate only 20 characters. After the capacity is reached, a new space for the StringBuilder will be allocated in the heap.

Setting StringBuilder capacity can increase performance dramatically but will use more memory if capacity is a lot larger than final string length.

Convert StringBuilder to String

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

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(10);
                sb.Append(“Hello ”);
                sb.Append(“John”);
                // Convert StringBuilder to string
                Console.WriteLine(Convert.ToString(sb));
                // or
                // Console.WriteLine(sb.ToString());
                 Console.ReadLine();
             }
}
// Output: Hello John

Conclusion

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

In summary, it is always a good idea to consider whether you need to modify or change the string or not. If you only need to read or compare strings, it is more efficient to use a String, as it is an immutable object. However, if you need to build or modify a string repeatedly, you should use a StringBuilder, as it is a mutable object that is more efficient for this purpose. It is important to choose the right type for your needs to ensure that your code is as efficient as possible. Keep in mind that StringBuilder may use more memory than strings in some cases.

References

johnskeet.uk/csharp/stringbuilder.html