Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the Dictionary is internally maintained?

Tags:

c#

dictionary

When i say

Dictionary<int,string>

is it equivalent to two different arrays such as:

int[] keys =new int[] { 1, 2, 3 };
string[] values=new string[]{"val1","val2","val3"};
like image 486
user193276 Avatar asked Oct 21 '09 12:10

user193276


2 Answers

That's not too far off. Looking at the source code in Reflector, it seems three internal collections are used:

private Entry<TKey, TValue>[] entries;
private KeyCollection<TKey, TValue> keys;
private ValueCollection<TKey, TValue> values;

Note that there is also a int[] buckets variable to keep track of the buckets required in the case of hash-code collisions.

These variables' purposes should all be fairly self-explanatory. This is not particularly surprising, anyway, since the Dictionary class is known and documented to provide (ideally, with one item per bucket) O(1) lookup time.

like image 54
Noldorin Avatar answered Sep 29 '22 15:09

Noldorin


It's all clearly written on MSDN:

The Dictionary(Of TKey, TValue) generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary(Of TKey, TValue) class is implemented as a hash table.

like image 33
Bolek Tekielski Avatar answered Sep 29 '22 15:09

Bolek Tekielski