LINQ 环:Any() 与 Contains() 用于巨大的集合 [英] LINQ Ring: Any() vs Contains() for Huge Collections

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

问题描述

给定大量对象,以下是否有性能差异?

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() 是一个实例方法,其性能很大程度上取决于集合本身.例如,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屋!

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