String and StringBuilder are yet another concept in C# which often goes neglected. Everytime a programmer has to save some string into a variable, they simply declare a string in their program and use it. But in the long term and in big projects, it often leads to high memory consumption. In this article, we will explain why this happen and how to avoid it using StringBuilder.

The difference between string and StringBuilder in C# is a very important concept which can help programmers and developers in understanding and coding in a better and optimized manner. This is also one of the most important questions in terms of interview specially at fresher level.

String

In C#, string is used to store a series of characters together. For eg., if we would like to get the URL of this site from console, we will write a simple program like:

When we compile this program, it will be used as shown below:

String in C#

Now if we want to add the extension then it will modify the program by adding a simple line  (line no. 16):

With an addition of extra line, we simply added the extension to same string. But this led to weak memory management. For instance, if first string occupied a space of X Bytes, and after adding the extension it occupied Y Bytes, then in total X+Y bytes is occupied in this operation. This is because String is immutable type. By immutable, it means that once a string object has been created then it cannot be modified. Any operations which we will perform on it such as insert, replace, append etc. (i.e. any operation which requires to change the string), then it will discard the old value and a new instance of it will be created in memory to hold that up. To solve this, we have StringBuilder in C#

StringBuilder

String builder in C# can be considered as mutable string. This means that if we have created StringBuilder object once, then we can perform any operations such as append, replace, insert without creating a new instance of it every time.

Have a look at below example

 Now the above program will only occupy Y bytes in total after adding extension and output will be:
StringBuilder in C#

So for quick reference, here are the differences between String and StringBuilder:

String

StringBuilder

It is immutable It is mutable
In terms of performance, string is slow as new instance is created everytime In terms of performance, StringBuilder is comparatively fast as same instance is used.
In string we don’t have append keyword In StringBuilder we can use append keyword
String belongs to System namespace Stringbuilder belongs to System.Text namespace
We hope that you will find this explanation useful and handy. Also, we are welcome to new suggestions. Drop your queries below.



ABOUT THE AUTHOR:

Software Developer by profession, Ankit is a Microsoft Certified Professional and beholds certification for 'Microsoft Specialist: Programming in C#'. Follow him at Facebook | Twitter | Google + | Android


Tags: , , , , , ,

Leave A Response