Should you use Any, Contains or Exists in C#?

Have you ever wondered which one of Any, Contains or Exists you should use, and why they had to “give birth” to 3 of them like that! Now let’s take a look together at why. Let’s go!

Which one to use?

When working with List, IEnumerable or array, using the Contains method takes full advantage of their efficiency thanks to the way they’re designed internally (linear search based on index, using a basic for loop), guaranteeing the highest performance.

As for Exists, we can only use it with List or arrays. It uses the same linear search mechanism as above, but now it takes in a delegate as a parameter to check the condition (enumerator), which leads to it being slower than Contains.

On the other hand, LINQ’s Any method can be applied to every kind of IEnumerable (List inherits from this so it still works, and it’s the same for array), which brings a lot of flexibility.

However, that very flexibility is what makes Any run slower than Exists, because it has to create an enumerator + use foreach, plus there are some other costs on top (checking conditions to throw exceptions and so on).

What all three of these methods have in common is that they all search linearly with O(n) complexity.

A small note, Contains, if used carelessly, especially when you don’t clearly understand pass by reference vs pass by value (in Vietnamese), can easily blow up on you => don’t use Contains to check against a list or array of object (reference) type. Whereas with Any and Exists, when we write the comparison condition, we already have a clear idea of what we’re comparing.

For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System.Collections.Generic;
using System.Linq;

public class Program
{
static void Main(string[] args)
{
var listNumber = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

listNumber.Contains(6);
listNumber.Exists(a => a == 6);
listNumber.Any(a => a == 6);
}
}

In summary

To wrap it up, if you know exactly what you’re comparing, if you’re comparing values, then prefer Contains, and conversely if you’re working with List or an array go with Exists. And if you need a more general method that can be used on many different kinds of collections, Any will be the sensible choice.

Speed comparison

Here’s the speed comparison of the three against each other (list, array, ienumerable with 10000 elements of type int), look at columns 1, 2 and 5, taking ListAny as the baseline:

image

 Comments
Comment plugin failed to load
Loading comment plugin