Examine some FxCop warnings related to performance and understand them. FxCop is a static analysis tool by Microsoft that will help us improve our code. We must make our code more efficient and robust, and we should learn to watch for warnings and act on them. We need to understand the warning signs.
FxCop performs analysis of the intermediate language to notify you of possible or definite flaws in your code. Detailed analysis of functions, and profiling of them, can be useless. However, if this analysis can bring you a more nuanced understanding of the code, it is worthwhile.
Reference types are initialized to null if they are member variables, and int values are automatically initialized to 0. FxCop should complain, and it does sometimes. [CA1805, DoNotInitializeUnnecessarily]
// These assignments are not necessary, and you had better hope I
// never see you doing them.
class Box
{
int _cat = 0;
string _make = null;
}
I have seen this error in example code in books. The key here is that the as operator will return null if it fails. Here I show the slow code that triggers this warning, and then the faster code that avoids multiple casts. [CA1800, DoNotCastUnnecessarily]
// See if the object IS of the type being tested.
if (thisObject is CertainClass)
{
// Now, let's do that over again but store the value.
// Do not do this.
CertainClass c = thisObject as CertainClass;
// Do something with the object.
}
The next block here is how to solve the "DoNotCast..." warning. We must use "as" to cast and then test for null. This eliminates one cast in the success case, and doesn't cost much if the cast fails.
// This is the ideal code, as it allows you to test if the object IS
// of the type, and then get the object AS the type. Use this.
CertainClass c = thisObject as CertainClass;
if (c != null)
{
// Good job.
}
To solve this, I suggest you use the string.IsNullOrEmpty method, which is a static function you call using the string class. It returns true or false depending on whether the string is empty. Microsoft encourages it, and it makes for simpler code. (Testing empty strings for Length is the fastest method.) [CA1820, TestForEmptyStringsUsingStringLength]
// See if the specified string is null, or if it is empty.
// Both cases are detected in IsNullOrEmpty. This is very efficient.
string valueString = null;
if (string.IsNullOrEmpty(valueString) == true)
{
Console.WriteLine("The string is null or empty.");
}
Start using Microsoft FxCop 1.36 Beta 2 every few days on your programs. It will teach you a lot and show you ways to analyze and improve your code. Every character in your C# code can have an impact far greater than you might think. The benefits to your projects will soon become apparent.