String Vs StringBuilder In C#

Introduction

The difference between String and Stringbuilder is one of the most  frequently asked question in all the interviews and all of us answer something similar.

Original Article link : Difference Between String And StringBuilder In C#


Quote

String is immutable and StringBuilder is mutable

This is a one word answer. In this blog, I would like to dig  into things in more detail.

Don’t Ignore Basics

Both String and Stringbuilder represent a sequence of characters. When we list out their differences, some of us don’t remember the basic difference. String class is in the system namespace while StringBuilder is in System.Text.

Sometimes Mute is Safe

Let us make the statement again “String is immutable and StringBuilder is mutable” [Don’t be confused about which one is mutable and which one is not].

Immutability of string object means, if any of your operations on the string instance changes it value, it will end up in the creation of new instance in a different address location with the modified value. Mutability of StringBuilder is just opposite for this. It won’t create a new instance, when their content changes as a string does. Instead, it makes the new changes in the same instance.

Mutability and immutability of these two can be understood from C# program, given below.
  1. //for String Class    
  2. using System;    
  3. //for StringBuilder Class    
  4. using System.Text;    
  5.     
  6. class Program    
  7. {    
  8.   static void Main(string[] args)    
  9.   {    
  10.     String str = "My first string was ";  
  11.     str += "Hello World";  
  12.     //Now str="My first string was Hello World"    
  13.     StringBuilder sbr = new StringBuilder("My Favourite Programming Font is ");//line-13    
  14.     sbr.Append("Inconsolata");//line-14    
  15.     //Now sbr="My Favourite Programming Font is Inconsolata"    
  16.     Console.ReadKey();    
  17.   }    
  18. }    

 
In line 11 content of str changes, new instance is created in a different memory location with the new value, as shown in the image, above.

Even though line 14 changes the value of stringbuilder variable sbr, it won’t create a new one. Instead, it will keep appending new strings to the existing instance. See how it looks in terms of memory.



Because of this behavior of StringBuilder, it is also known as mutable string.

I am not convinced


If you say, I’m not convinced, let us check these behaviors, using C# code snippet. For it, I am using C# class ObjectIDGenerator(in System.Runtime.Serialization Namespace). Actually, it will return a unique integer value for the instances, which we created in our programs. With the help of this class, we can check whether new instance is created or not for the various operations on String and Stringbuilder. Consider the program, given below.
  1. using System;    
  2. using System.Text;    
  3. using System.Runtime.Serialization;    
  4.     
  5. class Program    
  6. {    
  7.   static void Main(string[] args)    
  8.   {    
  9.     ObjectIDGenerator idGenerator = new ObjectIDGenerator();    
  10.     bool blStatus = new bool();    
  11.     //just ignore this blStatus Now.    
  12.     String str = "My first string was ";    
  13.     Console.WriteLine("str = {0}", str);    
  14.     Console.WriteLine("Instance Id : {0}", idGenerator.GetId(str, out blStatus));    
  15.     //here blStatus get True for new instace otherwise it will be false    
  16.     Console.WriteLine("this instance is new : {0}\n", blStatus);    
  17.     str += "Hello World";    
  18.     Console.WriteLine("str = {0}", str);    
  19.     Console.WriteLine("Instance Id : {0}", idGenerator.GetId(str, out blStatus));    
  20.     Console.WriteLine("this instance is new : {0}\n", blStatus);    
  21.     //Now str="My first string was Hello World"    
  22.     StringBuilder sbr = new StringBuilder("My Favourate Programming Font is ");    
  23.     Console.WriteLine("sbr = {0}", sbr);    
  24.     Console.WriteLine("Instance Id : {0}", idGenerator.GetId(sbr, out blStatus));    
  25.     Console.WriteLine("this instance is new : {0}\n", blStatus);    
  26.     sbr.Append("Inconsolata");    
  27.     Console.WriteLine("sbr = {0}", sbr);    
  28.     Console.WriteLine("Instance Id : {0}", idGenerator.GetId(sbr, out blStatus));    
  29.     Console.WriteLine("this instance is new : {0}\n", blStatus);    
  30.     //Now sbr="My Favourate Programming Font is Inconsolata"    
  31.     Console.ReadKey();    
  32.   }    
  33. }   
Output will look, as shown below.



Did you see that..? Instance Id for the string changed from 1 to 2 when str concatenated with “Hello World”, while instance Id of sbr remains the same as 3, after appending operation also. This tells all about mutability and immutability. blStatus variable indicates whether the instance is new or not. Now, you are convinced right?

Who Runs Faster?

Let’s discuss the performance difference between String and Stringbuilder. The code box, given below will explain things in a better way. Before that, if you don’t know how to measure execution time in C#, you can read my article here.
  1. using System;    
  2. using System.Text;    
  3. using System.Diagnostics;    
  4.     
  5. class Program    
  6. {    
  7.   static void Main(string[] args)    
  8.   {    
  9.     Stopwatch Mytimer = new Stopwatch();    
  10.     string str = string.Empty;    
  11.     Mytimer.Start();    
  12.     for (int i = 0; i < 10000; i++)    
  13.     {    
  14.         str += i.ToString();    
  15.     }    
  16.     Mytimer.Stop();    
  17.     Console.WriteLine("Time taken by string : {0}", Mytimer.Elapsed);    
  18.     StringBuilder sbr = new StringBuilder(string.Empty);    
  19.     //restart timer from zero    
  20.     Mytimer.Restart();    
  21.     for (int i = 0; i < 10000; i++)    
  22.     {    
  23.         sbr.Append(i.ToString());    
  24.     }    
  25.     Mytimer.Stop();    
  26.     Console.WriteLine("Time taken by stringbuilder : {0}", Mytimer.Elapsed);    
  27.     Console.ReadKey();    
  28.   }    
  29. }   
Output of this program looks, as given below.



This output clearly shows their performance difference. StringBuilder is about 70X faster than String in my laptop. It might be different in your case but generally speaking Stringbuilder gives 10x times speed than String.

One Last Thing

"New Instance of string will be created only when its value changes."

If you do an operation on a string variable, creation of new instance occurs only when it’s current value changes. Try the code, given below.
  1. using System;    
  2. using System.Text;    
  3. using System.Runtime.Serialization;    
  4.     
  5. class Program    
  6. {    
  7.   static void Main(string[] args)    
  8.   {    
  9.     ObjectIDGenerator idGenerator = new ObjectIDGenerator();    
  10.     bool blStatus = new bool();    
  11.     string str = "Fashion Fades,Style Remains Same";    
  12.     Console.WriteLine("initial state");    
  13.     Console.WriteLine("str = {0}", str);    
  14.     Console.WriteLine("instance id : {0}", idGenerator.GetId(str, out blStatus));    
  15.     Console.WriteLine("this is new instance : {0}", blStatus);    
  16.     //a series of operations that won't change value of str    
  17.     str += "";    
  18.     //try to replace character 'x' which is not present in str so no change    
  19.     str = str.Replace('x''Q');    
  20.     //trim removes whitespaces from both ends so no change    
  21.     str = str.Trim();    
  22.     str = str.Trim();    
  23.     Console.WriteLine("\nfinal state");    
  24.     Console.WriteLine("str = {0}", str);    
  25.     Console.WriteLine("instance id : {0}", idGenerator.GetId(str, out blStatus));    
  26.     Console.WriteLine("this is new instance : {0}", blStatus);    
  27.     Console.ReadKey();    
  28.   }    
  29. }  
Output



Initial and final Id is 1, which means new instance is not created for these operations, since it does not change the value of str. You may wonder about how the compiler shows this intelligence.

More Reference

Original Article link : Difference Between String And StringBuilder In C#

video tutorial :-