16

I'm trying to understand if there are any performance hit in using an OrderBy clause before Where clause like so:

List<string> names = new List<string> { //... };

var ns = names.OrderBy(n => n).Where(n => n.Length == 5);

Or will the compiler rearrange instructions so the Where clause gets executed before OrderBy clause?

Saravana
  • 37,852
  • 18
  • 100
  • 108
  • Compile the code and check in ILDASM the final code generated in both the cases – Guanxi May 25 '13 at 04:30
  • http://blogs.msdn.com/b/csharpfaq/archive/2009/01/26/does-the-linq-to-objects-provider-have-built-in-performance-optimization.aspx – dotNET May 25 '13 at 04:52

1 Answers1

16

That really depends on the LINQ provider (the class that implements IQueryable<T>).

On Entity Framework and LINQ to SQL (and other database related LINQ providers), the query is converted to SQL statements, and then will run on the database engine. For example, this query:

var ns = names.OrderBy(n => n).Where(n => n.Length == 5);

when iterated over, will be converted to:

SELECT * FROM names WHERE LEN(name) == 5 ORDER BY name

no matter where you put the OrderBy clause.

So in this case, there is no performance hit. But when using LINQ to Objects (as in your example), the two variations have a lot of difference in performance. This answer form Jon Skeet covers this case pretty well.

Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72