C # - Search for dictionary keys and search values ​​in a list

In terms of search speed, is it better to look for dictionary keys or list values?

In other words, which one would be most preferable?

Dictionary<tring,string> dic = new Dictionary<string,string>();
if(dic.ContainsKey("needle")){ ... }

or

List<string> list = new List<string>();
if(list.Contains("needle")){ ... }
+4
source share
3 answers

If “better” means “faster,” use a dictionary. Dictionary keys are organized by hash codes, so search queries are significantly faster than a list search with more than a few elements in ocllection.

O (1), . , O (n), , ( ) .

( ), HashSet. O (1) Value .

(, , , , , ?)

+6

Dictionary, . List, .

For searches, a dictionary is usually the best choice. The required time is flat, O (1) constant time complexity. The list has a linear time complexity of O (N). Three elements can loop faster than looking in a dictionary.

+2
source

Source: https://habr.com/ru/post/1523975/


All Articles