Difference between String and StringBuilder in C#

This article explains the differences between String and StringBuilder in C#, as well as when to use each. Their justifications will assist us in deciding what should be used in our code to handle memory management and string operations.


The String class provides many methods for safely creating, manipulating, and comparing strings. In addition, the C# language overloads some operators to simplify common string operations. When using the String class, each time you modify a string you must repeatedly reconstruct the full string in memory. By contrast, StringBuilder allocates a memory buffer space and applies updates to that buffer space.


Since the StringBuilder object is changeable, it performs faster than the String object when performing extensive string manipulation. Since String operations produce intermediate garbage instances after each operation, they consume more memory than StringBuilder operations.


String in C# :


The String in C# is an object of String type whose value is text. A string is a series of characters that is used to represent text. The string is efficient if we are only concatenating two or three strings.

When you can specify everything that needs to be concatenated in a single statement, use the string concatenation operator.

The string instance is immutable. Immutable means once we create a string object we cannot modify the value of the string Object in the memory. Any operation that seems to change the string will remove the previous value and save the new value in a new instance that is created in memory.


Declaration and Initialization of String :


In C# we can declare and initialize strings in this way, as shown in the following example:


Example :

using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {


            string str1 = "Welcome to CodeToSolutions!";


            Console.WriteLine(str1);


            // creates a new string instance

            str1 += "Hello";

            str1 += " World";


            Console.WriteLine( str1);

            Console.ReadLine();


        }

    }

}


Output :

Welcome to CodeToSolutions!

Welcome to CodeToSolutions! Hello World



string & System.String in C# :


The keyword "string" has very little functionality and is primarily used 

to create variables. Whereas, System. String is a class that gives you a rich set of functions and properties to manipulate the string.

There is no difference between string & String (with capital S) in C#. System. String (String with capital S) is a class in C# in the System namespace. string (with small s) is an alias of System. String.


Example :

using System;


using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {


            string FirstName = "CodeTo";

            String LastName = new String("Solutions");


            Console.WriteLine("First Name - " + FirstName);

            Console.WriteLine("Last Name - " + LastName);


            Console.WriteLine(FirstName.GetType().FullName);

            Console.WriteLine(LastName.GetType().FullName);


        }

    }

}



Output:

First Name - CodeTo

Last Name - Solutions

System.String

System.String


In the above mention code, FirstName and LastName are string variables, but FirstName is declared as a string with a small s, and LastName is declared as a System. String.

Each variable was given a value depending on its declaration, and we then printed the values and type information for both variables. A StringBuilder object cannot perform as many operations as you can do with a string.



Compare strings using StringComparison.OrdinalIgnoreCase :


Most often, individuals compare the two strings in the manner described below (regardless of whether they are written in upper- or lower-case).



if
(str1.ToLower() == str2.ToLower())

            {

                // do something                  

                Console.WriteLine("true");

            }


The compiler will experience increased memory allocation costs when comparing the two strings using the code above.


By avoiding string allocation costs like this, the aforementioned task can be completed.

if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))

            {

                // do something

                Console.WriteLine("Matched");

            }



StringBuilder in C# :


A StringBuilder is a changeable collection of characters in the C# programming language that can be expanded to store more characters as needed. A new instance of a StringBuilder is not created in memory when it is modified, unlike with strings.

Especially if you don't know for sure (at compilation time) how many rounds you'll make through the loop, use StringBuilder for concatenating strings in a very long loop or a loop of unknown size.

The System.Text.StringBuilder is mutable, which means once we create a StringBuilder object we can perform any operation that appears to change the value without creating a new instance every time. It can be modified in any way and it doesn't require the creation of a new instance.


Below is an example of StringBuilder.

Example :

using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {


            StringBuilder str1 = new StringBuilder("");


            str1.Append("Welcome to CodeToSolutions!");

            str1.Append(" Hello World! ");


            string str2 = str1.ToString();


            Console.WriteLine(str2);

            Console.ReadLine();

        }

    }

}



Output :

Welcome to CodeToSolutions! Hello World!



Declaration and Initialization of StringBuilder:


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


using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {


            StringBuilder sb = new StringBuilder();

            //or

            StringBuilder sb1 = new StringBuilder("Hello World");


        }

    }

}


Output :

Hello World




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)



Example :

using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {


            StringBuilder strb = new StringBuilder();


            strb.Append(" CodeTo ");


            strb.Append("Solutions");


            //CONVERT STRINGBUILDER TO STRING

            Console.WriteLine(Convert.ToString(strb));

            //or

            // Console.WriteLine(sb.ToString());



             // CONVERT STRING TO STRINGBUILDER

            string s = "CodeToSolutions";

            StringBuilder sb = new StringBuilder();

            sb.Append(s);

            Console.WriteLine(s);



            Console.ReadLine();


        }

    }

}


Output:

CodeToSolutions




Convert string to StringBuilder :


To convert a String value to a StringBuilder object just append it using the append() method.


Example :

using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {

      

            string s = "CodeToSolutions";

            StringBuilder sb = new StringBuilder();

            sb.Append(s);

            Console.WriteLine(s);

            Console.ReadLine();

        }

    }

}



Output:

CodeToSolutions



Difference between String and StringBuilder :


  • The string is immutable which means it’s unchangeable. An immutable object cannot be modified. Whereas StringBuilder is mutable which means it’s changeable.

In C# the StringBuilder is the better option for concatenating multiple strings simultaneously.


  • The string can not be changed once it has been created.

Whereas StringBuilder will improve performance in cases where you make repeated modifications to a string or concatenate many strings together.

  • A string class is used when the value of the string will remain constant throughout the program or when there are very few adjustments necessary for it. Whereas StringBuilder is used when many repeated alterations or intensive operations must be performed on the string.

  • Immutable objects are by default thread-safe because their state can not be modified once created. Whereas StringBuilder is used when many repeated alterations or intensive operations must be performed on the string.

  • The string is slow as compared to StringBuilder based on performance. Whereas StringBuilder is fast compared to String.  Like it is faster than String while concatenating many strings together in a loop.

  • If we will try to change the value of the String object, it will create a new instance in a different memory location with the modified value. Whereas String builder is a dynamic object that allows you to expand the number of characters in the string. It doesn’t create a new object in the memory to accommodate the modified list.



Performance between String and StringBuilder:


The string is slow as compared to StringBuilder based on performance. Whereas StringBuilder is fast compared to String.  Like it is faster than String while concatenating many strings together in a loop.

                

Let us understand the above explanations with help of an example given below :


Code :

using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {

            string student = "David";


Stopwatch sw = new Stopwatch();

       

sw.
Start();


for (int i = 0; i < 100000; i++)

      
  {

         
   student = student + i;

       

}

      
  sw.
Stop();



StringBuilder sb = new StringBuilder("Hello World!");


Stopwatch sw2 = new Stopwatch();

       

sw2.
Start();


for (int i = 0; i < 100000; i++)

       

{

         
   sb.
Append(i);

       

}

        
sw2.
Stop();


  Console.WriteLine("Time Taken By String: "+ sw.ElapsedMilliseconds);

  Console.WriteLine("Time Taken By StringBuilder: "+ sw2.ElapsedMilliseconds);

          Console.ReadLine();


        }

    }

}



Output :

      Time Taken By String:  19995

      Time Taken By StringBuilder:  20



Methods in StringBuilder:


StringBuilder is used to support several methods that can be used to modify or manipulate the string in the StringBuilder class. Here are some of the methods that exist in StringBuilder to work on string manipulation.


Append()  - The method append adds a new string value based on the given information at the end of the current StringBuilder.


Example :

using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {

          

            StringBuilder sb = new StringBuilder();


            sb.Append("CodeTo ");


            sb.Append("Solutions");


            //Text appends with a new line

            sb.Append ("This is the new example of CodeToSolutions");


            Console.WriteLine(sb);

            Console.ReadLine();


        }

    }

}



Output :

CodeToSolutions

This is the new example of CodeToSolutions




AppendFormat() - The AppendFormat method in C# can be used to format the input string into a desired format. which the StringBuilder's representation of the string can append at the end.



Example :

using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {

           



            StringBuilder amountMsg = new StringBuilder("Your total amount is ");


            amountMsg.AppendFormat("{0:C} ", 45);   // for Currency

            amountMsg.AppendFormat("{0:N} ", 45);   // for Number

            amountMsg.AppendFormat("{0:X} ", 45);   // Hexadecimal


            Console.WriteLine(amountMsg);



        }

    }

}




Output :

Your total amount is $45.00 45.00 2D



Insert() - The StringBuilder object in C# can have a string or an object added to it at a specific location using the Insert method.

Here, we're adding a word to a StringBuilder object in position 11.



Example :

using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {

           

            StringBuilder sb = new StringBuilder("Welcome to Tutorial");


            sb.Insert(11, " CodeToSolutions ");


            Console.WriteLine(sb);

            Console.ReadLine();


        }

    }

}



Output :

  Welcome to  CodeToSolutions tutorial



Remove() - The StringBuilder's Remove method in C# removes the string with the provided length at the supplied index.



Example :

using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {


            StringBuilder sb = new StringBuilder("Welcome to CodeToSolutions Tutorial");

            sb.Remove(10, 16);

            Console.WriteLine(sb);

            Console.ReadLine();


        }

    }

}




Output :

Welcome to Tutorial



Replace() - All instances of a specified string within the StringBuilder object are replaced by a specified replacement string using the Replace method of the StringBuilder in C#.



Example :

using System;

using System.Text;

using System.Diagnostics;


namespace StringBuilderDemo

{

    internal class Program

    {

        static void Main(string[] args)

        {


            StringBuilder sb = new StringBuilder("Happy Coding ?");


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

            Console.WriteLine(sb);


            Console.ReadLine();


        }

    }

}



Output :

Happy Coding !



Conclusion :


   A string is preferred when you only need to make a few modifications or append.

But StringBuilder is favored over string when you need to make more than three or four modifications or append.

The string is slow as compared to StringBuilder based on performance. StringBuilder is fast compared to String.  Like it is faster than String while concatenating many strings together in a loop.

hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.
















Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee