LINQ环:任何()VS包含()的巨大集合 [英] LINQ Ring: Any() vs Contains() for Huge Collections

查看:154
本文介绍了LINQ环:任何()VS包含()的巨大集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于巨大的对象的集合

,有没有之间的性能差异的下面?

Col​​lection.Contains

  myCollection.Contains(myElement)

Enumerable.Any

  myCollection.Any(currentElement => currentElement == myElement)


解决方案

包含()是一个实例方法,其性能在很大程度上取决于集合本身。例如,包含()在名单为O(n),而包含()上HashSet的是O(1)。

任何()是一个扩展方法,并会简单地去通过收集,运用委托每个对象。因此,它有一个为O(n)。

的复杂性

任何()更灵活然而,由于你可以传递一个委托。载有()只能接受一个对象。

Given a huge collection of objects, is there a performance difference between the the following?

Collection.Contains:

myCollection.Contains(myElement)

Enumerable.Any:

myCollection.Any(currentElement => currentElement == myElement)

解决方案

Contains() is an instance method, and its performance depends largely on the collection itself. For instance, Contains() on a List is O(n), while Contains() on a HashSet is O(1).

Any() is an extension method, and will simply go through the collection, applying the delegate on every object. It therefore has a complexity of O(n).

Any() is more flexible however since you can pass a delegate. Contains() can only accept an object.

这篇关于LINQ环:任何()VS包含()的巨大集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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