Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LINQ know how to optimize "queries"?

Suppose I do something like

 var Ordered = MyList.OrderBy(x => x.prop1).ThenBy(x => x.prop2); 

Does MyList.OrderBy(x => x.prop1) return the filtered list, and then does it further filter that list by ThenBy(x => x.prop2)? In other words, is it equivalent to

var OrderedByProp1 = MyList.OrderBy(x => x.prop1);
var Ordered = OrderedByProp1.OrderBy(x => x.prop2);

???

Because obviously it's possible to optimize this by running a sorting algorithm with a comparator:

var Ordered = MyList.Sort( (x,y) => x.prop1 != y.prop1 ? x.prop1 < y.prop1 : ( x.prop2 < y.prop2 ) );

If it does do some sort of optimization and intermediate lists are not returned in the process, then how does it know how to do that? How do you write a class that optimizes chains of methods on itself? Makes no sense.

like image 572
Subpar Web Dev Avatar asked Jan 27 '16 20:01

Subpar Web Dev


People also ask

Does LINQ optimize?

Does LINQ do any optimization by sorting/converting data structures? Yes. There are all sorts of optimizations that take place throughout various LINQ methods.

Are LINQ queries faster?

Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code. So your experience is that LINQ is faster and makes code harder to read and to maintain?

What is the main advantage of using LINQ for database queries?

Advantages of LINQStandardized way of querying multiple data sources: The same LINQ syntax can be used to query multiple data sources. Compile time safety of queries: It provides type checking of objects at compile time. IntelliSense Support: LINQ provides IntelliSense for generic collections.


1 Answers

Does MyList.OrderBy(x => x.prop1) return the filtered list

No. LINQ methods (at least typically) return queries, not the results of executing those queries.

OrderBy just returns an object which, when you ask it for an item, will return the first item in the collection given a particular ordering. But until you actually ask it for a result it's not doing anything.

Note you can also get a decent idea as to what's going on by just looking at what OrderBy returns. It returns IOrderedEnumerable<T>. That interface has a method CreateOrderedEnumerable which:

Performs a subsequent ordering on the elements of an IOrderedEnumerable according to a key.

That method is what ThenBy uses to indicate that there is a subsequent ordering.

This means that you're building up all of the comparers that you want to be used, from the OrderBy and all ThenBy calls before you ever need to generate a single item in the result set.

For more specifics on exactly how you can go about creating this behavior, see Jon Skeet's blog series on the subject.

like image 189
Servy Avatar answered Oct 02 '22 08:10

Servy