Optimize your C# Application

1. StringBuilder: knowing when to use

The main difference between string and StringBuilder is that using the StringBuilder to modify a string without creating a new object can boost performance when concatenating many strings in a loop. If you have a loop that will make modification to a single string for many iterations, then a StringBuilder class is much faster than a string type. However, if you just want to append/insert something to a string, then a StringBuilder will be over power. In this case, a simple string type will work well.

2. Strings Compare: Non-Case Sensitive

When we compare two strings, usually we use the built-in equals() method for the comparison. In case of ignoring the cases, people use ToLower() or ToUpper() methods. However, ToLower() or ToUpper() are bottlenecks in performance. Here is a way to increase your applications: use string.Compare(str1, str2, true) == 0; for comparing two strings ignoring cases. If str1 and str2 are equal ignoring cases then result will return 0.

3. Strings Compare: “string.Empty “

It is normal to see people use .equals(“”) for comparing an empty string. A popular practice is that checking a string’s length to be 0 is faster than comparing it to an empty string. Using string.Empty will not make anysignificant performance improvement, but bringing you the readable optimization.

4. Using “List<>” instead of using “ArrayList”

Both List<> and ArrayList can store objects within the same list. The difference is that ArrayList can store multiple types of objects while List<> has to specify one type of object. Also, when you extract the object from the list, the List<> does not need to cast the variable to a proper type while ArrayList has to. Therefore, if
you are keeping the same type of variables in one ArrayList, you can gain a performance boost by using List<> instead.

5. “try catch” vs “if else”

The “try catch” block is used to catch exceptions that are beyond our controls, such as connection problem. The “if else” is one of the basic logic which is being used in both programming and reality. The “try catch” block helps to avoid error-prone calls or any errors that might slow down the application. According to the ‘KISS’ principle, using “try catch” to keep code “simple”, “clean” better than using “if else” statements. However, we should refactor our source code to require less “try catch” or “if else” statements. That should be the main concentrate of code optimization.

6. Replace divisions

Although this issue is not as common as above, you could benifit from it if you are playing with numeric operations such as multiplication, division. The C# language is relatively slow when it comes to division operations. There is an article written by “rob tillaart” from CodeProject: http://www.codeproject.com/KB/cs/FindMulShift.aspx. He introduces an alternative way called “Multiply Shift” in C# to optimize the performance.

7. Using sealed classes when there isn’t any derived class

The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations. — From “gicio” in ‘Performance Optimization in C#’

8. ‘for’ Loop vs. ‘foreach’ Loop

Again, this is from “gicio” in ‘Performance Optimization in C#’.

This code costs tooooo much:

foreach(DataRow currentDataRow in currentDataTable.Rows)

{

newDataTable.ImportRow(currentDataRow);

}

this code runs over 300 % faster (depends on rows count):

DataRow[] allRows = currentDataTable.Select();

foreach (DataRow currentDataRow in allRows)

{

newDataTable.ImportRow(currentDataRow);

}

Conclusion

As you can see these are very simple C# code optimizations and yet they can have a powerful impact on the performance of your application. If you know any other useful C# code optimization ideas, please let me know and I will add them to the list here.

This entry was posted on Wednesday, January 4th, 2012 at 5:39 am and is filed under C# ASP .NET. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

5 Responses to “Optimize your C# Application”

  1. Wordlistx Says:

    Skyzzx…

    Great blog post, saw on…

  2. windows internet explorer for mac Says:

    windows internet explorer for mac…

    […]Well I definitely liked studying it. This article procured by you is very helpful for accurate planning.[…]…

  3. Nagwa Says:

    Hah, ahotner interesting question. I would like to hear the word immutable come out of the candidate’s mouth. In .NET strings are immutable so you’re generally better off using StringBuilder (a mutable or changeable object) as it cuts down on the number of objects created. StringBuilder is typically 1 to 2 orders of magnitude faster than the code you have. If I’m a stickler I’d say your code will generate a compilation warning since s was used but never initialized but now I’m just being imaginative and picky.

  4. Nam Says:

    Hi,I’ve found this post and think is very nice and useful.can you pls liaepxn me basic steps to implement this solution e.g. in a webpage ? thanks a lot.Max.p.s. in my (few) leasure time I’m trying to create an interface to automate VM snapshot and export them for disaster recovery purposes (actually I’m doing it with a bash script).I’m trying to write it in C#

  5. cafelearn72 Says:

    […]The information mentioned in the article are some of the best available […]……

    […]The information mentioned in the article are some of the greatest available […]……

Leave a Reply

*