I'm writing a service where performance is essential, and I'm not sure what is the fastest thing. I have a few Objects (50-200) which each have an ID in them (ints, e.g. 84397 or 23845). Would it be faster to have a Dictionary, a List of KeyValue Pairs or a List with the indexes set to the IDs with the rest having null values or an array with the same idea?
Arraylists just store a set of objects (that can be accessed randomly). Dictionaries store pairs of objects. This makes array/lists more suitable when you have a group of objects in a set (prime numbers, colors, students, etc.). Dictionaries are better suited for showing relationships between a pair of objects.
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. So, it is wise to use a list data structure when you are concerned with the order of the data elements.
An array is just a sorted list of objects. A dictionary stores key-value pairs. There are no advantages or disadvantages, they are just two data structures, and you use the one you need.
A list is an ordered sequence of objects, whereas dictionaries are unordered sets. However, the main difference is that items in dictionaries are accessed via keys and not via their position.
It depends on which operation you want to execute. Let's assume that you want to find an object with a given ID.
myArray[84397]
is a constant-time operation O(1). Of course, this approach requires the most memory.Thus, in your situation, I would choose the dictionary, unless the marginally better performance of the huge array is really relevant in your case.
Dictionary<TKey, TValue>
uses a hash table internally so I think it would be the fastest one.
Dictionary versus List Lookup time
Also, for a more detailed explaination of the different collections, check out this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With