Kishlin Kishlin - 27 days ago 15
C# Question

C# Finding an element in a List

Let's say I have the following C# code

var my_list = new List<string>();
// Filling the list with tons of sentences.
string sentence = Console.ReadLine();


Is there any difference between doing either of the following ?

bool c1 = my_list.Contains(sentence);
bool c2 = my_list.Any(s => s == sentence);


I imagine the pure algorithmic behind isn't exactly the same. But what are the actual differences on my side? Is one way faster or more efficient than the other? Will one method sometime return true and the other false? What should I consider to pick one method or the other? Or is it purely up to me and both work in any situation?

Answer

The most upvoted answer isn't completely correct (and it's a reason big O doesn't always work). Any will be slower than Contains in this scenario (by about double).

Any will have an extra call every iteration, the delegate you specified on every item in your list, something contain does not have to do. An extra call will slow it down substantially.

The results will be the same, but the speed will be very different.

Example benchmark:

Stopwatch watch = new Stopwatch();

List<string> stringList = new List<string>();

for (int i = 0; i < 10000000; i++)
{
    stringList.Add(i.ToString());
}
int t = 0;
watch.Start();
for (int i = 0; i < 1000000; i++)
    if (stringList.Any(x => x == "29"))
        t = i;

watch.Stop();
("Any takes: " + watch.ElapsedMilliseconds).Dump();
GC.Collect();
watch.Restart();

for (int i = 0; i < 1000000; i++)
    if (stringList.Contains("29"))
        t = i;

watch.Stop();

("Contains takes: " + watch.ElapsedMilliseconds).Dump();

Results:

Any takes: 481
Contains takes: 235

Size and amount of iterations will not effect the % difference, Any will always be slower.