LINQ 环:Any() 与 Contains() 用于巨大的集合 [英] LINQ Ring: Any() vs Contains() for Huge Collections
问题描述
给定大量对象,以下是否有性能差异?
Given a huge collection of objects, is there a performance difference between the the following?
myCollection.Contains(myElement)
myCollection.Any(currentElement => currentElement == myElement)
推荐答案
Contains()
是一个实例方法,其性能很大程度上取决于集合本身.例如,List
上的 Contains()
是 O(n),而 HashSet
上的 Contains()
是 O(1).
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()
是一个扩展方法,它将简单地遍历集合,将委托应用于每个对象.因此它的复杂度为 O(n).
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()
更灵活,因为您可以传递委托.Contains()
只能接受一个对象.
Any()
is more flexible however since you can pass a delegate. Contains()
can only accept an object.
这篇关于LINQ 环:Any() 与 Contains() 用于巨大的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!