Basically, as the question states… does the order of LINQ functions matter in terms of performance? Obviously the results would have to be identical still…
Example:
myCollection.OrderBy(item => item.CreatedDate).Where(item => item.Code > 3);
myCollection.Where(item => item.Code > 3).OrderBy(item => item.CreatedDate);
Both return me the same results, but are in a different LINQ order. I realize that reordering some items will result in different results, and I’m not concerned about those. What my main concern is in knowing if, in getting the same results, ordering can impact performance. And, not just on the 2 LINQ calls I made (OrderBy, Where), but on any LINQ calls.
It will depend on the LINQ provider in use. For LINQ to Objects, that could certainly make a huge difference. Assume we’ve actually got:
That requires the whole collection to be sorted and then filtered. If we had a million items, only one of which had a code greater than 3, we’d be wasting a lot of time ordering results which would be thrown away.
Compare that with the reversed operation, filtering first:
This time we’re only ordering the filtered results, which in the sample case of “just a single item matching the filter” will be a lot more efficient – both in time and space.
It also could make a difference in whether the query executes correctly or not. Consider:
That’s fine – we know we’ll never be dividing by 0. But if we perform the ordering before the filtering, the query will throw an exception.