Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Dictionary<Foo, Foo> Instead of List<Foo> to Speed up Calls to Contains()

I have a question about generic collections in C#. If I need to store a collection of items, and I'm frequently going to need to check whether an item is in the collection, would it be faster to use Dictionary instead of List?

I've heard that checking if an item is in the collection is linear relative to the size for lists and constant relative to the size for dictionaries. Is using Dictionary and then setting Key and Value to the same object for each key-value pair something that other programmers frequently do in this situation?

Thanks for taking the time to read this.

like image 209
Newell Clark Avatar asked May 15 '12 20:05

Newell Clark


People also ask

Is dictionary faster than list Python?

A dictionary is 6.6 times faster than a list when we lookup in 100 items.

Why use a dictionary instead of a list in Python?

Therefore, the dictionary is faster than a list in Python. It is more efficient to use dictionaries for the lookup of elements as it is faster than a list and takes less time to traverse. Moreover, lists keep the order of the elements while dictionary does not.

Why dictionary is faster than list?

The reason is because a dictionary is a lookup, while a list is an iteration. Dictionary uses a hash lookup, while your list requires walking through the list until it finds the result from beginning to the result each time.

What does dictionary items () do in Python?

In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Parameters: This method takes no parameters. Returns: A view object that displays a list of a given dictionary's (key, value) tuple pair.


1 Answers

Yes, yes it is. That said, you probably want to use HashSet because you don't need both a key and a value, you just need a set of items.

It's also worth noting that Dictionary was added in C# 2.0, and HashSet was added in 3.5, so for all that time inbetween it was actually fairly common to use a Dictionary when you wanted a Set just because that was all you had (without rolling your own). When I was forced to do this I just stuck null in the value, rather than the item as the key and value, but the idea is the same.

like image 166
Servy Avatar answered Nov 05 '22 13:11

Servy