LINQ中是否有多个.Where()语句是性能问题? [英] Is multiple .Where() statements in LINQ a performance issue?

查看:203
本文介绍了LINQ中是否有多个.Where()语句是性能问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道多个.Where()语句是否会对性能产生影响.例如,我可以写:

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
                )
        );

或者我可以将它们全部合并到一个Where()子句中,如下所示:

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
                )
        );

Where()子句链会影响性能还是等同于它们?

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

推荐答案

在LINQ to Objects中,对性能的影响很小,因为基本上迭代器链会更长-获取下一个元素意味着要沿着长链前进的MoveNext()调用.

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.

在LINQ to SQL和类似的提供程序中,我希望以相同的方式生成相同的SQL,因此它不会影响那里的性能.

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.

自编写此书以来,我发现了有关LINQ to Objects实现的更多信息-它是

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

这篇关于LINQ中是否有多个.Where()语句是性能问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆