C# Tips

Expensive strings and stringBuilder class in C#


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.

Diagnostic Tools in C#

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.