- Home /
Array of dictionaries or one massive dictionary?
Alright, I'm facing this decision. Should I make an array of dictionaries, where each element in an array would be a dictionary, and to access it I'd call
dictionaryArray[index]["dictionary_key"] = "foo";
or instead have a massive dictionary and use the index as a prefix?
massiveDictionary[index+"dictionary_key"] = "foo";
I'm asking mainly, because I don't know what the algorithms of generic dictionaries are, and whether the increasing number of elements impacts their performance or not.
--David--
The first one will be faster, due to the second having a slow (in comparison) string-concatenation. But, there is likely a better overall solution to your problem. What is the actual problem you're trying to solve?
Answer by DocteurCox · Jun 26, 2013 at 08:28 PM
The Dictionary 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 class is implemented as a hash table. Note The speed of retrieval depends on the quality of the hashing algorithm of the type specified for TKey.
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
I think performances should not be a major issue :)
Wow, I didn't know dictionaries were O(1) access time. Anyways, thanks for the pointer :) I'll test this out and then comment with my final solution.
Technically, dictionary access is not O(1), it's amortized ("average") O(1). Array-access is for real-real O(1). In either case, as I mentioned above, the bottleneck for this piece of code is going to be the string-concatenation, which will likely be slower than either of those access-patterns.
However, I agree with @DocteurCox that this is highly unlikely to be the bottleneck in your program, unless you are calling it on the order of 100,000+ times per frame.
So, it probably won't make a difference.
Ok, again, I thank you both for your inputs on this ;)
Your answer
Follow this Question
Related Questions
Load txt file (CSV) into Generic Dictionary Javascript 1 Answer
Storing level data from a texture file, and drawing at speed. 0 Answers
Can Vexe.FastSave save dictionaries to files? 1 Answer
Is it possible to change the element name in an Array List? 1 Answer
Array member treated as null even though it is not. 1 Answer