Are there any performance difference between these 2 linq queries, are they identical or essentially different?
Also, does the order of where clause matter?
from x in A.where(x=>CriteriaA(x))
from y in B where(y=>CriteriaB(y))
where CriteriaC(x,y)
from x in A
from y in B
where(x=>CriteriaA(x))
where(y=>CriteriaB(y))
where CriteriaC(x,y)
from x in A
from y in B
where(y=>CriteriaB(y))
where(x=>CriteriaA(x))
where CriteriaC(x,y)
Update: All are IEnumerable<> and Linq to Objects
Use Jon Skeet's scenario: A has 100 entries, 25 of which match CriteriaA B has a 100 entries, 50 of which match CriteriaB
1st first method, there will be 100 calls to CriteriaA
, 2500 calls to CriteriaB
, and 12开发者_开发问答50 calls to CriteriaC
.
2nd method, there will be 10000 calls to CriteriaA
, 2500 calls to CriteriaB
, and 1250 calls to CriteriaC
.
3rd method, there will be 10000 calls to CriteriaB
, 5000 calls to CriteriaA
, and 1250 Calls to CriteriaC
.
Is that correct?
It will partly depend on whether this is LINQ to Objects, LINQ to SQL etc. Let's assume LINQ to Objects.
Imagine this scenario:
A
has 100 entries, 25 of which match CriteriaAB
has a 100 entries, 50 of which match CriteriaB
Then in the first scenario, there will be 100 calls to CriteriaA, 2500 calls to CriteriaB, and 1250 calls to CriteriaC.
In the second scenario, there will be 10,000 calls to CriteriaA, 2500 calls to CriteriaB, and 1250 calls to CriteriaC.
If you "materialize" the results of one Where
call like this:
var resultsB = B.Where(y => CriteriaB(y)).ToList();
from x in A.Where(x => CriteriaA(x)).ToList()
from y in resultsB
where CriteriaC(x,y)
Then there will be 100 calls to CriteriaA, 100 calls to CriteriaB, and the same 1250 calls to CriteriaC. Obviously that will take more memory as it has to cache the results
I would expect the first to be faster because less data is fetched.
But it may depend on the datasets, and of course it matters whether this is about IEnumerable<>
or IQueryable<>
.
If you really want to know: measure.
精彩评论