Optimizing C#

2009-04-13


I got part of content from vcskicks.com

7 Ways To Optimize C# Code

1. Use StringBuilder or String ?

StringBuilder is faster mostly with big strings. This means if you have a loop that will add to a single string for many iterations then a StringBuilder class is definitely much faster than a string type.

However if you just want to append something to a string a single time then a StringBuilder class is overkill. A simple string type variable in this case improves on resources use and readability of the C# source code.

2. Comparing Non-Case-Sensitive Strings

if(str1.ToLower() == str2.ToLower()) ...

But better use this way:

To check if two strings are equal ignoring case would look like this:

string.Compare(str1, str2, true) == 0 //Ignoring cases

The C# string.Compare function returns an integer that is equal to 0 when the two strings are equal.

3. Use string.Empty

Try to replace lines like:

if (str == "")

with:

if (str == string.Empty)

This is simply better programming practice and has no negative impact on performance.

Note, there is a popular practice that checking a string's length to be 0 is faster than comparing it to an empty string. While that might have been true once it is no longer a significant performance improvement. Instead stick with string.Empty.

4. Replace ArrayList with List<>

5. Use && and || operators

if (object1 != null && object1.runMethod())

If object1 is null, with the && operator, object1.runMethod()will not execute. If the && operator is replaced with &, object1.runMethod() will run even if object1 is already known to be null, causing an exception.

6. Smart Try-Catch

Using a try statement to keep code "simple" instead of using if statements to avoid error-prone calls makes code incredibly slower. Restructure your source code to require less try statements.

7. Replace Divisions

C# is relatively slow when it comes to division operations. One alternative is to replace divisions with a multiplication-shift operation to further optimize C#. The article explains in detail how to make the conversion. Conclusion