Everyone wants faster performance of application and we are been asked frequently on every .net forums that
- “How Can I Improve performance of C# Application”
- “How Can I Improve performance of ASP.net Application”
Well there are many ways but out of them we can also improve performance of .Net Application by avoiding unnecessary string creation
A System.String object is “immutable”. “Immutable” means, any change to a string requires creating a new string object. Unnecessary string creation degrades the performance.
Step1: Avoid Empty string Assignment
Bad Programming
String strMyString = “”;
//It creates an additional empty string, before assignment.
Good Programming
String strMyString = string.Empty;
//It doesn’t require to creates an additional empty string, before assignment.
Step2: Use Case-Insensitive String Comparison or Avoid unnecessary changes to string.
Many times we have habbit of casing the string before comparing, but casing the string creates a new string object. To avoid that use Case-Insensitive string comparison.
Bad Programming
if (strCheck.ToLower() == “yes”)
//It creates new string with strCheck content as lower and assign it.
Good Programming
if (System.String.Compare(strCheck,”yes”,true) == 0)
//System.String.Compare method returns Zero when strings are equal.
One step ahead of our discussion.
In above example you will notice that “yes” is a content which is been used to compare, but think if this comparison is made number of times, and at some point we need to change the comparison criteria from “yes” to “no” in that case it would be tedious task to replace each “yes” with “no”, moreover it is not 100% reliable.
To avoid such situation, one should always declare such data as constant, so changing its value will be reflected to all the places where it is been used.
Let consider above example, in that case you should create a class form, let say “clsConstant” wherein all the constants are been declared.
In clsConstant.cs File
public static string YES = "yes";
In form where it is used.
if (System.String.Compare(strCheck, clsConstant.YES,true) == 0)
Step3: Use StringBuilder class for string concatenations and manipulations.
Strings are immutable, means when you modify string it creates a new string based on your modification. Original string will be therein memory till it is garbage collected. So if your application requires extensive modification of strings, you should use StringBuilder class instead of using String class, as stringbuilder class object is mutable and does in-place modification of string.
Bad Programming
String strResult = “”;
String strAppend = “ABC”;
for( int iCount = 0; iCount < 50; iCount++)
{
strResult = strResult + strAppend;
}
//Here 50 times string is modified, and created
Good Programming
string strResult=string.Empty;
string strAppend = "ABC";
StringBuilder sb = new StringBuilder(strResult);
for(int iCount=0; iCount < 50; iCount++)
{
sb.Append(strAppend);
}
strResult = sb.ToString();