Monday, April 28, 2008

Sorting Performance of Dynamic Linq

I have really just started scratching the surface of Linq & C# 3.5. One thing that I was instantly dissapointed was how the sorting is implemented. In my web application all of our grids are sortable and prior to Linq I wrote a little IComparer implementation which uses reflection to access any property we need.

The issue I have with the linq implementation is that if the columns we are sorting on can change, I would have to have different lambda expression for all the possible permutations. This is not acceptable.

The Dynamic Linq Library is included in the C# Linq Samples. I highly recommend looking into the dynamic library. It allows for the lambda expressions to be expressed using a very easy to learn syntax, which is stored as a string. This allows you at runtime to easily build dynamic expressions for example:


lines.AsQueryable().OrderBy(field + " " + direction.ToString());




How does this perform compared to the reflection based implementation? I have not done a full analysis and only have time for a quick look at it but from what I have it is not to bad. For the record I am running a 2.5GHZ Dual Core Intel with 3 GB of Ram running on Windows Vista. We will be sorting 100 classes in a List<> object. The classes have two integer properties which were randomly seeded.

As expected the first pass through the code is the most expensive but how expensive is it?

  • Dyanmic Linq: 15.5 MS
  • Reflection: 5.5 MS
  • Linq Query: .87 MS

This is expected since the Dyamic Linq is building the expression trees. If your only going to sort a list once then going with reflection here might be more appropiate due to the 300% overhead of the dyanmic query; however, what happens if you end up sorting the same collection 100 times. For this test, I decided to sort the same list each time only I would swap between two different integer properties.


  • Dynamic Linq: 26 MS
  • Reflection: 195 MS
  • Linq Query:1.87 MS


I was shocked by this. I had thought that by changing the dyanmic expression it would have to re-initalize itself. Looks like I was wrong. A normal linq query is definetly the fastest approach; however, I feel that due to its inflexibility, the dynamic approach is a better aproach.

No comments: