23 December 2011

String is Immutable in C# and Java, Use of String builder in C#

String is Immutable in C# and Java, Use of String builder in C#

In C# a string is immutable and cannot be altered. When you alter a string, you are actually creating a new string, which in turn uses more memory than necessary, creates more work for the garbage collector and makes the code execution run slower. When a string is being modified frequently it begins to be a burden on performance .This seemingly innocent example below creates three string objects.

string msg = "Your total is ";//String object 1 is created
msg += "$500 ";            //String object 2 is created
msg += DateTime.Now();   //String object 3 is created

StringBuilder is a string-like object whose value is a mutable sequence of characters. The value is said to be mutable because it can be modified once it has been created by appending, removing, replacing, or inserting characters. You would modify the above code like this.

StringBuilder sb = new StringBuilder();
sb.Append("Your total is ");
sb.Append("$500 ");
sb.Append(DateTime.Now());

The individual characters in the value of a StringBuilder can be accessed with the Chars property. Index positions start from zero.



No comments:

Post a Comment

Comments Welcome

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...