Sunday, April 12, 2009

8 Ways to Optimize Your C# Application 2/2

Ways to optimize C# code in .NET development

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: 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)

this code runs over 300 % faster (depends on rows count):
DataRow[] allRows = currentDataTable.Select();
foreach (DataRow currentDataRow in allRows)


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.

8 Ways to Optimize Your C# Application 1/2


0 Responses to "8 Ways to Optimize Your C# Application 2/2"

Post a Comment



Copyright 2009 All Rights Reserved Revolution Two Lifestyle theme by Brian Gardner | Blogger template converted & enhanced by eBlog Templates