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

SDReyes picture SDReyes · Dec 15, 2010 · Viewed 60.7k times · Source

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)

Answer

Etienne de Martel picture Etienne de Martel · Dec 15, 2010

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.