Understand String vs String Builder in C-sharp

String Vs StringBuilder

Below are most important difference between "String" and "String Builder". 

Lets Discuss below.

Difference-1

"String Builder" is Mutable where as string is immutable. 

Mutable - You can change it.

Immutable - You cannot change it.

When we need to add more number of string to the variable that case we will use "String Builder" in stead of string. Lets understand Why?

See the below Code.


using System;
using System.Text;
namespace TestApplication{  
    class Program
    {
        
        public static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();  //Using string builder
            sb.Append("Hi Raj");
            sb.Append("How Are You");
            sb.Append("?");

            string mystring="Hi Raj";                   //using string
            mystring = mystring + "How Are You";
            mystring = mystring + "?";

            Console.WriteLine(mystring + " -----" + sb.ToString());
            int i=mystring.CompareTo(sb.ToString());
            if (i == 0)
                Console.WriteLine("Both strings are same");
            else
                Console.WriteLine("Both strings different");  
            Console.ReadKey();
        }         
    }
}




Lets see the output.


Fig-1


See the Highlighted part---- both Strings are same.


The output is same for both. Then what is the Need of "String Builder" in this case?


Lets discuss the performance of string and "String builder".


Let see the below Images.

Fig-2

Fig-3
Fig-2 Represents String where as Fig-3 Represents String Builder.
For each string concatenation, "String" create a different memory location and store the Value as shown in Fig-2. For storing 3 values "string" create 3 memory location. That is the reason why it is called as Immutable.

In case of "String Builder" for each concatenation value will be replace in the same memory location as shown in Fig-3. That is the reason why it is called as mutable.


We can represent the string and string builder in a simple way as below.


Fig-4
See Fig-4 Multiple objects gets created for "String" when we add multiple strings but for "String Builder" only one object gets created.

Difference-2

String Builder use System.Text Namespace.
String Use System namespace.

Difference -3

String builder need to convert to string while displaying.
String no need to convert to any type.


Thanks................


Share:

No comments:

Post a Comment

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts