0

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?

8
  • 1
    Considering there is nothing populated in my_list, both will return false in about the same amount of time. If you want to find out which is faster, you could try debugging and testing which one returns a false faster, although under the shown conditions it is highly unlikely for you to get a valid result. Commented Nov 8, 2016 at 17:15
  • @vipersassassin did you read this line? // Filling the list with tons of sentences. Commented Nov 8, 2016 at 17:15
  • you decide which is faster Commented Nov 8, 2016 at 17:15
  • 1
    I suggest that you read the source code of each if you want to know how they differ. Commented Nov 8, 2016 at 17:16
  • 2
    @AlfieGoodacre, for Contains it does not matter, you have to explicitly call List<T>.BinarySearch(string) for you to get the benefit. Here is the source code for Contains Commented Nov 8, 2016 at 17:18

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Realistically, the two will operate in almost the same fashion: iterate the list's items and check to see if sentence matches any list elements, giving a complexity of about O(n). I would argue List.Contains since that is a little easier and more natural, but it's entirely preferential!

Now, if you're looking for something faster in terms of lookup complexity and speed, I'd suggest a HashSet<T>. HashSets have, generally speaking, a lookup of about O(1) since the hashing function, theoretically, should be a constant time operation. Again, just a suggestion :)

1 Comment

Okay so it's almost only up to one's preferences. That's what I wanted to know, thanks. :)
1

For string objects, there's no difference, since the == operator simply calls String.Equals.

However, for other objects, there could be differences between == and .Equals - looking at the implementation of .Contains, it will use the EqualityComparer<T>.Default, which hooks into Equals(T) as long as you class implements IEquatable<T> (where T is itself). Without overloading ==, most classes instead use referential comparison for == since that's what they inherit from Object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.