torsdag, mars 04, 2010

Performance nightmare

22 to 0.3 seconds!

I found a simple solution to a very common problem. While profiling I found that remove in this little method took a lot of the time.
   public void MovePropertyFirst(IProperty property)
{
properties.Remove(property);
properties.Insert(0, property);
}

The reason was, that it's time consuming to compare the properties by equality, for complex types. I think that in most(?) cases we want to delete the very same instance we supply as parameter to the remove method.

So I implemented a ReferenceEquals based remove, and by that I cut the time spent in remove by about 72 times!

public static bool RemoveFrom<T>(this IList<T> list, T itemToRemove)
{
if(list.Count == 0)
return false;
int index = 0;
foreach (var item in list)
{
if (ReferenceEquals(item, itemToRemove))
{
list.RemoveAt(index);
return true;
}
index++;
}
Debug.Assert(false, "Item to delete not found");
//equality based fall back
return list.Remove(itemToRemove);
}