Search Chirayu Software Solutions Blog

Tuesday, April 22, 2014

Tips for optimizing c# code

1) Capacity

For collections, you can use an optional capacity argument to influence the initial buffer sizes. It is best to pass a reasonable parameter when creating a Dictionary or List. This avoids many allocations when adding elements.

2) Lookup tables

While switch statements or hashtables can provide good performance, using a lookup table is frequently the optimal choice. Instead of testing each character using logic to lowercase, you can translate it through a lookup table.

3) Do not use clear in dictionary or list

4) Use String.Compare instead of =’s

When doing a case-insensitive compare, the String.Compare function provides far greater performance than using the equals operator and two case modifying functions.
bool match = s1.ToLower() == s2.ToLower();

bool match = (string.Compare(s1, s2, true) == 0);

5. Use string.Empty

This is not so much a performance improvement as it is a readability improvement, but it still counts as code optimization. Try to replace lines like:

if (str == "")

if (str == string.Empty)

Post a Comment