If I chain clauses such as
var results = elements
.Where(n => n > 3)
.Where(n => n % 2 == 0);
is this slower than just
var results = elements.Where(n => n > 3 && n % 2 == 0);
Explain why or why not?
EDIT: It seems that the consensus is that even POCO objects iterate twice. If this is the case can someone explain why Microsoft wouldn’t combine these predicates. I stumbled across Enumerable.CombinePredicates that I thought did this. Can someone please explain what this does then.
Edit:
I looked a little closer. The
WhereEnumerableIteratorreturned by theWhereextension method actually overrides theWheremethod and combines the predicates into a single callback.So, the speed difference I saw on my machine should probably be attributed to something else.
The first example will loop over the
elementscollection once to find items that satisfy the conditionitem > 3, and again to find items that satisfy the conditionitem % 2 == 0.The second example will loop over the
elementscollection once to find items that satisfy the conditionitem > 3 && item % 2 == 0.In the examples provided, the second will most likely always be faster than the first, because it only loops over
elementsonce.Here is an example of some pretty consistent results I get on my machine (.NET 3.5):
Results:
EDIT:
@Rawling is right in that my explanation only applies to LINQ as used on collections of POCO objects. When used as an interface to LINQ-to-SQL, NHibernate, EF, etc., your results will be more implementation-dependent.