As Windows software developers, we have a tendency to focus on user interface elements, sometimes to the exclusion of program efficiency and performance.
Recently, I was performing a code review on a program that was keeping a list of class instances. I worked out an example file and profiled the program execution. My example took nearly 45 seconds to complete! Ouch!
The developer was using a list of class instances to store data values (much like a multidimensional array). I won't get into the debate of multi-dimensional arrays versus a list of class instances, it doesn't really matter. What does matter is the developer needed to find a particular class instance in the list of classes (often). The developer was using the following psuedo code:
bool FindInstance(CClassInstance CI)
{
foreach (CClassIntance t in ListofInstances)
{
if (t.Property1 == CI.Property1)
return true;
else
return false;
}
}
While there is nothing programmatically wrong with this code, it was the largest consumer of CPU cycles when I ran a performance profile in VS 2008. The routine was called a lot, and it looped a lot. Neither is particularly efficent.
Had the developer implemented the IComparer interface, his code would have performed much more efficiently. The list could have been sorted once, and BinarySearch could had been used to determine if the instance existed in the list:
public class CClassInstanceComparer : IComparer<CClassInstance>
{
public int Compare(CClassInstance a, CClassInstance b)
{
if (a.Property1 == b.Property1)
return 0;
elseif (a.Property1 < b.Property1)
return -1;
elseif (a.Property1 > b.Property1)
return 1;
}
}
// In the calling code:
// ....
// Implement the following, rather than calling FindInstance
CClassInstanceComparer_compare = new CClassInstanceComparer();
ListofInstances.Sort(_compare);
// Do some more stuff
// ....
// Finally, see if an instance exists.
if (0 == ListofInstances.BinarySearch(_instanceToSearch, _compare))
{
// Do something
}
else
{
// Do something else
}
The sort and binary search code executed a little over 100 times faster, causing a complex calculation to improve some 45 seconds to less than .5 seconds. (In this case, the list of class instances was over 10,000, which caused lengthy linear searches to occur.)
The moral of this story is it pays to know the details of .Net. Spend some time and learn the simple stuff.