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.
- //for String Class
- using System;
- //for StringBuilder Class
- using System.Text;
- class Program
- {
- static void Main(string[] args)
- {
- String str = "My first string was ";
- str += "Hello World";
- //Now str="My first string was Hello World"
- StringBuilder sbr = new StringBuilder("My Favourite Programming Font is ");//line-13
- sbr.Append("Inconsolata");//line-14
- //Now sbr="My Favourite Programming Font is Inconsolata"
- Console.ReadKey();
- }
- }

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.
- using System;
- using System.Text;
- using System.Runtime.Serialization;
- class Program
- {
- static void Main(string[] args)
- {
- ObjectIDGenerator idGenerator = new ObjectIDGenerator();
- bool blStatus = new bool();
- //just ignore this blStatus Now.
- String str = "My first string was ";
- Console.WriteLine("str = {0}", str);
- Console.WriteLine("Instance Id : {0}", idGenerator.GetId(str, out blStatus));
- //here blStatus get True for new instace otherwise it will be false
- Console.WriteLine("this instance is new : {0}\n", blStatus);
- str += "Hello World";
- Console.WriteLine("str = {0}", str);
- Console.WriteLine("Instance Id : {0}", idGenerator.GetId(str, out blStatus));
- Console.WriteLine("this instance is new : {0}\n", blStatus);
- //Now str="My first string was Hello World"
- StringBuilder sbr = new StringBuilder("My Favourate Programming Font is ");
- Console.WriteLine("sbr = {0}", sbr);
- Console.WriteLine("Instance Id : {0}", idGenerator.GetId(sbr, out blStatus));
- Console.WriteLine("this instance is new : {0}\n", blStatus);
- sbr.Append("Inconsolata");
- Console.WriteLine("sbr = {0}", sbr);
- Console.WriteLine("Instance Id : {0}", idGenerator.GetId(sbr, out blStatus));
- Console.WriteLine("this instance is new : {0}\n", blStatus);
- //Now sbr="My Favourate Programming Font is Inconsolata"
- Console.ReadKey();
- }
- }

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.
- using System;
- using System.Text;
- using System.Diagnostics;
- class Program
- {
- static void Main(string[] args)
- {
- Stopwatch Mytimer = new Stopwatch();
- string str = string.Empty;
- Mytimer.Start();
- for (int i = 0; i < 10000; i++)
- {
- str += i.ToString();
- }
- Mytimer.Stop();
- Console.WriteLine("Time taken by string : {0}", Mytimer.Elapsed);
- StringBuilder sbr = new StringBuilder(string.Empty);
- //restart timer from zero
- Mytimer.Restart();
- for (int i = 0; i < 10000; i++)
- {
- sbr.Append(i.ToString());
- }
- Mytimer.Stop();
- Console.WriteLine("Time taken by stringbuilder : {0}", Mytimer.Elapsed);
- Console.ReadKey();
- }
- }

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.
- using System;
- using System.Text;
- using System.Runtime.Serialization;
- class Program
- {
- static void Main(string[] args)
- {
- ObjectIDGenerator idGenerator = new ObjectIDGenerator();
- bool blStatus = new bool();
- string str = "Fashion Fades,Style Remains Same";
- Console.WriteLine("initial state");
- Console.WriteLine("str = {0}", str);
- Console.WriteLine("instance id : {0}", idGenerator.GetId(str, out blStatus));
- Console.WriteLine("this is new instance : {0}", blStatus);
- //a series of operations that won't change value of str
- str += "";
- //try to replace character 'x' which is not present in str so no change
- str = str.Replace('x', 'Q');
- //trim removes whitespaces from both ends so no change
- str = str.Trim();
- str = str.Trim();
- Console.WriteLine("\nfinal state");
- Console.WriteLine("str = {0}", str);
- Console.WriteLine("instance id : {0}", idGenerator.GetId(str, out blStatus));
- Console.WriteLine("this is new instance : {0}", blStatus);
- Console.ReadKey();
- }
- }

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 :-

bhupender bishtPosted Nov 14, 2016, 9:47 AM
Great one..and reference of ObjectIDGenerator class is useful..
Omid NasriPosted Oct 22, 2016, 4:20 PM
Good one
Anand MorePosted Oct 19, 2016, 2:58 AM
Very well explained...thanks Sameer
Surya KantPosted Oct 19, 2016, 1:06 AM
Well explained. Image with your view is so much clear that any one can understand. Thanks.
Bikesh SrivastavaPosted Oct 18, 2016, 11:26 PM
Good
Mahesh ChandPosted Oct 18, 2016, 9:38 PM
Nice Sameer. Love your graphics and presentation style. Very clear. Thanks.
Raja TPosted Oct 18, 2016, 1:41 PM
Nice .... thanks for sharing
Anil Kumar MurmuPosted Oct 18, 2016, 12:16 PM
@Kmiilo, as per my understanding, if you are performing lots of string concatenation then go for StringBuilder. Since, it would not create multiple objects for each concatenation operation. Otherwise using string is fine.
Kmiilo MontoyaPosted Oct 18, 2016, 10:57 AM
I do not quite understand. you could solve my doubt?StringBuilder can be used as a good practice in each property of a model or what situation the use of this class may be feasible?
Anil Kumar MurmuPosted Oct 18, 2016, 12:11 AM
Very good article. ObjectIDGenerator class is new for me. Thank you for sharing your thoughts.
AniPosted Oct 17, 2016, 5:07 AM
Thanks for well explained article