As we know strings are a group of characters, usually composed of letters, numerals and special symbols etc. C# string type is immutable object, i.e, they can be created once, after that they can’t be modified.
Immutable string
Usually you may argue that it is a non sense, I am talking about. Let’s consider the following line of code
string str=” Some string”
str+=” Some other string”
Here firstly we created string variable str and add some initial string value and trying to add new string “Some other string” with the old one. Even Though there is + operator appeared after the variable, the string variable can’t be modified, instead C# will create a new string by combining the both strings. As a result more and more memory occupied.
Build mutable strings with StringBuilder
This problem can be simply fixed with in built C# class StringBuilder which is mutable object. Following example will clarify the idea. Create a console application which will execute a series of sample string for a specific times, say 1000.
string str=””;
for(int i = 0; i <= 10000; i++)
{
str += “Sample C# string”;
}
Console.WriteLine(“String numbers are:” + str);
Console.ReadKey();
Above code will result in extravagant use of memory and may slash the speed of the program, by using the string builder, it can be rewritten as ,
string str=””;
StringBuilder sb = new StringBuilder() ;
for(int i = 0; i <= 10000; i++)
{
sb.Append (” Sample C# strings “);
}
str = sb.ToString();
Console.WriteLine(“String numbers are:” + str);
Console.ReadKey();
Open the Diagnostic Tool in Visual Studio 2013/15 to find out memory usage. As the program get more complex you can find out that StringBuilder uses less memory than immutable string. StringBuilder also come with