Is multiple .Where() statements in LINQ a performance issue?

≡放荡痞女 提交于 2019-12-08 14:35:43

问题


I am wondering if there are performance implications of multiple .Where() statements. For example I could write:

var contracts =  Context.Contract
    .Where(
        c1 =>
            c1.EmployeeId == employeeId
        )
    .Where(
        c1 =>
            !Context.Contract.Any(
                c2 =>
                    c2.EmployeeId == employeeId
                    && c1.StoreId == c2.StoreId
                    && SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
                )
        )
    .Where(
        c1 =>
            !Context.EmployeeTask.Any(
                t =>
                    t.ContractId == c1.Id
                )
        );

Or alternatively I could combine them all into the one Where() clause, like so:

var contracts =  Context.Contract
    .Where(
        c1 =>
            c1.EmployeeId == employeeId
            && !Context.Contract.Any(
                c2 =>
                    c2.EmployeeId == employeeId
                    && c1.StoreId == c2.StoreId
                    && SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
                )
            && !Context.Employee_Task.Any(
                t =>
                    t.ContractId == c1.Id
                )
        );

Does the chain of Where() clauses hurt performance or are they equivalent?


回答1:


In LINQ to Objects, there will be a very small performance hit, because basically the iterator chain will be longer - fetching the next element means going up a long chain of MoveNext() calls.

In LINQ to SQL and similar providers, I'd expect the same SQL to be generated either way, so it wouldn't impact performance there.

EDIT: Since writing this I've found out a bit more about the LINQ to Objects implementation - it's a little more complicated...



来源:https://stackoverflow.com/questions/4735531/is-multiple-where-statements-in-linq-a-performance-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!