Generic Sorting and poor late bound performance - a solution?

<offtopic>What a month!  Relocated the family to Washington DC, fought with the DC DMV, finally closed on the first house we have ever sold and got the flu!</offtopic>

In case, you missed it - I wrote this article on Generic Sorting on AspAlliance recently.  It demonstrates a technique I use frequently in applications and I was really surprised to see the incredibly poor performance that late binding introduces when used over and over again in something like a sorting algorithm.  This led me to experiment with caching the late bound results (something I have never done in any of the production applications that use this technique) -  I was mildly satisfied with the caching results and consoled myself with the idea that performance in sorting within your applications is probably not a big issue unless it is used frequently and your application is under really heavy load.

Enter Keith J. Farmer who read my article and suggested the concept used by regular expressions - compile the sorters!  What an interesting idea!  Instead of doing all the comparisons using late binding - the developer would specify the sorting logic to use (e.g. by the “Name” property descending and “Age” property ascending) and then request that the “factory” create a sorter.  This would mean that the factory would also have to know the type of the instances it will be sorting (the type that defines the properties for sorting) and then would have to build the class from code, compile it (CODEDOM?) and then create an instance and return it.

The use case for the code might be something like:

PropertyComparerFactory factory = new PropertyComparerFactory(typeof(Person));

factory.SortByProperty(“Name“, CompareOrder.Ascending);

factory.SortByProperty(“Age“, CompareOrder.Descending);

PropertyComparer comparer = factory.CreateInstance();

Arrays.Sort(people, comparer);

Neither Keith nor I have tried this idea out yet with real code but I hope to do so soon. :-D

Comments, ideas and discussion are welcome as always.

1 Comment

  • Sounds like an excellent idea. I've done something similar with Filters for my collections. Rather then looping over all the items in a collection and comparing a single property to the all important value I have a factory method create the &quot;Collection Finder.&quot; Similar to what your talking about and works great!

Comments have been disabled for this content.