LINQ Ring: Any() vs Contains() for Huge Collections

心已入冬 提交于 2019-11-26 20:28:07

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.

It depends on the collection. If you have an ordered collection then Contains might do a smart search (binary, hash, b-tree, etc.) while with Any() you are basically stuck with enumerating until you find it (assuming LINQ to Objects)

Also note that in your example Any() is using the "==" operator which will check for referential equality while Contains will use IEquitable or the Equals() method which might be overriden.

I suppose that would depend on the type of myCollection is which dictates how Contains() is implemented. If a sorted binary tree for example, it could search smarter. Also it may take the element's hash into account. Any() on the other hand will enumerate through the collection until the first element that satisfies the condition is found. There are no optimizations for if the object had a smarter search method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!