Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#

String Vs StringBuilder in C#

Rate me:
Please Sign up or sign in to vote.
3.48/5 (20 votes)
1 May 2017CPOL3 min read 36K   17   25
In this article I would like to discuss all about string vs strinbuilder in C#

Introduction

Difference between string and stringbuilder is one of the frequently asked question in all interviews and all of us answer something in common

Quote:

String is Immutable and StringBuilder is Mutable

This is a one word answer. In this article I would like to dig things in more details.

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

Don’t Ignore Basics 

Both String and Stringbuilder represent sequence of characters. When we list out their differences some of us don’t remember basic difference. That is 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 operation on the string instance changes it’s value, it will end up in the creation of new instance in a different address location with modified value. Mutability of StringBuilder is just opposite for this.It won’t create new instance when their content changes as string does.Instead it makes the new changes in the same instance.

Mutability and Immutability of these two can be understood from following C# Program.

//for String Class
using System;
//for StringBuilder Class
using System.Text;

class Program
{
  static void Main(string[] args)
  {
    String str = "My first string was ";//line-10
    str += "Hello World";//line-11
    //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, so new instance is created in a different memory location with new value as shown in above image.

Even Though line 14 changes the value of stringbuilder variable sbr it won’t create a new instead it will keep appending new strings to existing instance.see how it looks in terms of memory

Because of this behaviour of StringBuilder it also known as Mutable String.

I am not convinced

If you say I’m not convinced. let us check these behaviours using  C# code snippet. For that I am using C# class ObjectIDGenerator(in System.Runtime.Serialization Namespace). Actually it will return an unique integer value for instances that we created in our programs.With the help of this class we can check whether new instance is created or not for various operations on string and stringbuilder .Consider following program

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();
  }
}

Output Will look like this

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

Who Run Faster?

Let’s discuss performance difference between string and stringbuilder.The following code box 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 from 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();
  }
}

Output of this program was

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

Quote:

New Instance of string will be created only when it’s value changes

One more thing,If you do an operation on a string variable, Creation of new instance occurs only when it’s current value changes.try following code,

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();
  }
}

Output!

initial and final id is 1-means new instance is not created for these operation since it does not change the value of str. You may wonder about how compiler shows this much intelligence.

More Reference

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

video tutorial :-

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
passionate .net developer

my blog : http://dotnetmob.com/
my video tutorial : https://www.youtube.com/c/DotnetMob




Comments and Discussions

 
Praisegood one Pin
prao20162-May-17 15:32
prao20162-May-17 15:32 
Question[My vote of 1] The Scenarios are not quite real, performance is a complex thing Pin
AndyHo2-May-17 5:15
professionalAndyHo2-May-17 5:15 
GeneralMy vote of 5 Pin
prashita gupta1-May-17 21:27
prashita gupta1-May-17 21:27 
SuggestionImages do not show in article Pin
E. Anderson1-May-17 11:01
E. Anderson1-May-17 11:01 
QuestionRead the documentation... Pin
Philippe Mori24-Oct-16 12:57
Philippe Mori24-Oct-16 12:57 
AnswerRe: Read the documentation... Pin
hooodaticus25-Oct-16 10:31
hooodaticus25-Oct-16 10:31 
True, although the better way to build a log file is with a FileStream reading log inputs from a lock-free queue. Allocating big chunks of memory to assemble a running log causes memory use to spike and drop when it's generally better to have a flat memory consumption curve.
QuestionMutability of Strings in C# Pin
hooodaticus14-Oct-16 7:57
hooodaticus14-Oct-16 7:57 
AnswerRe: Mutability of Strings in C# Pin
Philippe Mori24-Oct-16 12:58
Philippe Mori24-Oct-16 12:58 
GeneralRe: Mutability of Strings in C# Pin
hooodaticus25-Oct-16 10:34
hooodaticus25-Oct-16 10:34 
QuestionPerformance of StringBuilder is not as good as you tested, it is far worse! Pin
AndyHo14-Oct-16 5:05
professionalAndyHo14-Oct-16 5:05 
AnswerRe: Performance of StringBuilder is not as good as you tested, it is far worse! Pin
the Kris14-Oct-16 10:52
the Kris14-Oct-16 10:52 
GeneralRe: Performance of StringBuilder is not as good as you tested, it is far worse! Pin
AndyHo1-Dec-16 4:44
professionalAndyHo1-Dec-16 4:44 
QuestionPerformance od StringBuilder is not as good as you tested, it is worse! Pin
AndyHo14-Oct-16 5:05
professionalAndyHo14-Oct-16 5:05 
GeneralMy vote of 5 Pin
Moshe Morris13-Oct-16 4:19
Moshe Morris13-Oct-16 4:19 
GeneralRe: My vote of 5 Pin
Shamseer K13-Oct-16 6:03
professionalShamseer K13-Oct-16 6:03 
GeneralRe: My vote of 5 Pin
Moshe Morris13-Oct-16 6:37
Moshe Morris13-Oct-16 6:37 
GeneralRe: My vote of 5 Pin
Shamseer K13-Oct-16 14:59
professionalShamseer K13-Oct-16 14:59 
QuestionA word on performance Pin
Klaus Luedenscheidt12-Oct-16 19:34
Klaus Luedenscheidt12-Oct-16 19:34 
GeneralPerformance Pin
InbarBarkai12-Oct-16 19:10
InbarBarkai12-Oct-16 19:10 
GeneralRe: Performance Pin
irneb13-Oct-16 23:39
irneb13-Oct-16 23:39 
GeneralRe: Performance Pin
InbarBarkai24-Oct-16 19:28
InbarBarkai24-Oct-16 19:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.