LINQ 函数的顺序重要吗? [英] Does the order of LINQ functions matter?

查看:35
本文介绍了LINQ 函数的顺序重要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,正如问题所述... LINQ 函数的顺序对性能有影响吗?显然,结果仍然必须相同...

Basically, as the question states... does the order of LINQ functions matter in terms of performance? Obviously the results would have to be identical still...

示例:

myCollection.OrderBy(item => item.CreatedDate).Where(item => item.Code > 3);
myCollection.Where(item => item.Code > 3).OrderBy(item => item.CreatedDate);

两者都返回相同的结果,但 LINQ 顺序不同.我意识到重新排序某些项目会导致不同的结果,我并不关心这些.我主要关心的是知道在获得相同的结果时,排序是否会影响性能.而且,不仅在我进行的 2 个 LINQ 调用(OrderBy、Where)上,而且在任何 LINQ 调用上.

Both return me the same results, but are in a different LINQ order. I realize that reordering some items will result in different results, and I'm not concerned about those. What my main concern is in knowing if, in getting the same results, ordering can impact performance. And, not just on the 2 LINQ calls I made (OrderBy, Where), but on any LINQ calls.

推荐答案

这将取决于所使用的 LINQ 提供程序.对于 LINQ to Objects,这肯定会产生巨大的不同.假设我们实际上有:

It will depend on the LINQ provider in use. For LINQ to Objects, that could certainly make a huge difference. Assume we've actually got:

var query = myCollection.OrderBy(item => item.CreatedDate)
                        .Where(item => item.Code > 3);

var result = query.Last();

这需要对整个集合进行排序并然后过滤.如果我们有一百万件商品,其中只有一个商品的代码大于 3,那么我们将浪费大量时间订购会被丢弃的结果.

That requires the whole collection to be sorted and then filtered. If we had a million items, only one of which had a code greater than 3, we'd be wasting a lot of time ordering results which would be thrown away.

与反向操作相比,先过滤:

Compare that with the reversed operation, filtering first:

var query = myCollection.Where(item => item.Code > 3)
                        .OrderBy(item => item.CreatedDate);

var result = query.Last();

这次我们只对过滤后的结果进行排序,在仅单个项目与过滤器匹配"的示例情况下,这将更加高效 - 无论是在时间上还是空间上.

This time we're only ordering the filtered results, which in the sample case of "just a single item matching the filter" will be a lot more efficient - both in time and space.

它还可以对查询是否正确执行产生影响.考虑:

It also could make a difference in whether the query executes correctly or not. Consider:

var query = myCollection.Where(item => item.Code != 0)
                        .OrderBy(item => 10 / item.Code);

var result = query.Last();

没关系 - 我们知道我们永远不会除以 0.但是如果我们在过滤之前执行排序,查询将抛出异常.

That's fine - we know we'll never be dividing by 0. But if we perform the ordering before the filtering, the query will throw an exception.

这篇关于LINQ 函数的顺序重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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