Given a huge collection of objects, is there a performance difference between the the following?
myCollection.Contains(myElement)
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.