.where(...).Any()与..Any(...)之间的性能差异 [英] Performance difference between .where(...).Any() vs ..Any(...)

查看:314
本文介绍了.where(...).Any()与..Any(...)之间的性能差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
LINQ扩展方法-Any()vs. Where()vs. Exists( )

给出内存中的对象列表,我运行以下两个表达式:

myList.where(x => x.Name == "bla").Any() 

vs

myList.Any(x => x.Name == "bla")

后者始终是最快的,我认为这是由于Where枚举了所有项目.但是,如果没有匹配项,也会发生这种情况.

我不确定确切的原因.在任何情况下都不会出现这种看似的性能差异,例如是否在查询Nhib?

干杯.

解决方案

带有谓词的Any()可以在没有迭代器(yield return)的情况下执行其任务.使用Where()创建一个迭代器,添加该迭代器会对性能产生影响(尽管很小).

因此,就性能而言(略微),最好使用带有谓词(x => x.Name == "bla")的Any()形式.就我个人而言,我发现它也更具可读性...

另一方面,Where()不一定会枚举所有元素,它只是创建一个迭代器,该迭代器将在元素被请求时遍历元素,因此在Where()之后对Any()的调用将驱动迭代,它将在找到的第一个与条件匹配的项目处停止.

因此,性能差异不是不是,因为Where()遍历所有项(在linq-to-objects中),因为实际上并不需要(除非当然,它找不到满足它的对象),这是因为Where()子句必须设置一个迭代器以遍历元素,而带有谓词的Any()则不需要.

Possible Duplicate:
LINQ extension methods - Any() vs. Where() vs. Exists()

Given a list of objects in memory I ran the following two expressions:

myList.where(x => x.Name == "bla").Any() 

vs

myList.Any(x => x.Name == "bla")

The latter was fastest always, I believe this is due to the Where enumerating all items. But this also happens when there's no matches.

Im not sure of the exact WHY though. Are there any cases where this viewed performance difference wouldn't be the case, like if it was querying Nhib?

Cheers.

解决方案

The Any() with the predicate can perform its task without an iterator (yield return). Using a Where() creates an iterator, which adds has a performance impact (albeit very small).

Thus, performance-wise (by a bit), you're better off using the form of Any() that takes the predicate (x => x.Name == "bla"). Which, personally, I find more readable as well...

On a side note, Where() does not necessarily enumerate over all elements, it just creates an iterator that will travel over the elements as they are requested, thus the call to Any() after the Where() will drive the iteration, which will stop at the first item it finds that matches the condition.

So the performance difference is not that Where() iterates over all the items (in linq-to-objects) because it really doesn't need to (unless, of course, it doesn't find one that satisfies it), it's that the Where() clause has to set up an iterator to walk over the elements, whereas Any() with a predicate does not.

这篇关于.where(...).Any()与..Any(...)之间的性能差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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