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?
No, that order doesn't matter (or at least: shouldn't matter). Any decent query optimizer will look at all the parts of the WHERE clause and figure out the most efficient way to satisfy that query.
The ORDER BY clause is used to get the sorted records on one or more columns in ascending or descending order. The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query.
A where clause will generally increase the performance of the database. Generally, it is more expensive to return data and filter in the application. The database can optimize the query, using indexes and partitions. The database may be running in parallel, executing the query in parallel.
ORDER BY is always put at the very end of the query. Clauses like FROM , WHERE , GROUP BY , HAVING , etc. should be put before the ORDER BY keyword. To sort the output in ascending order, you may put the keyword ASC after the column name.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With