简体   繁体   中英

LINQ performance question when joining IEnumerable with IQueryable

I had some serious speed issues with the LINQ in this code (variable names have been changed)

var A = _service.GetA(param1, param2); // Returns Enumerable results

var results = (from b in _B.All() // _B.All() returns IQueryable
        join c in _C.All() on b.Id equals c.Id // _C.All() returns IQueryable
        join a in A on a.Id equals c.Id
        where b.someId == id && a.boolVariable // A bool value
        select new
        {
          ...
        }).ToList();

This LINQ took over 10 seconds to execute even though the number of rows in B and C tables were less than 100k.

I looked into this and by trial and error I managed to get the LINQ execution time to 200ms by changing the code to this:

var A = _service.GetA(param1, param2).Where(a => a.boolVariable); // Returns Enumerable results

var results = (from b in _B.All() // _B.All() returns IQueryable
        join c in _C.All() on b.Id equals c.Id // _C.All() returns IQueryable
        join a in A on a.Id equals c.Id
        where b.someId == id
        select new
        {
          ...
        }).ToList();

So my question is, why does this simple change have such drastic effects on the LINQ performance? The only change is that I filter the Enumerable list beforehand, the A enumerable has about 30 items before filtering and 15 after filtering.

In your first scenario: first it joins all the records in A which would take long time to join, then filters out for a.boolVariable .

In your second scenario you have a smaller subset of records for A prior to joining - of course this would take less time to join.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM