Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary, List or Array? [closed]

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?

like image 340
SBoss Avatar asked Nov 29 '11 07:11

SBoss


People also ask

Is dictionary better than array?

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.

Which is better dictionary or list?

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.

What is the difference between an array and a dictionary?

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.

What is the difference between a list and a dictionary?

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.


3 Answers

It depends on which operation you want to execute. Let's assume that you want to find an object with a given ID.

  • The huge array approach is fastest: Accessing myArray[84397] is a constant-time operation O(1). Of course, this approach requires the most memory.
  • The dictionary is almost as fast but requires less memory, since it uses a hash table internally.
  • The list of pairs approach is the slowest, since you might have to traverse the whole list to find your entry, which yields O(n) complexity.

Thus, in your situation, I would choose the dictionary, unless the marginally better performance of the huge array is really relevant in your case.

like image 66
Heinzi Avatar answered Nov 07 '22 07:11

Heinzi


Dictionary<TKey, TValue> uses a hash table internally so I think it would be the fastest one.

like image 23
Haris Hasan Avatar answered Nov 07 '22 08:11

Haris Hasan


Dictionary versus List Lookup time

Also, for a more detailed explaination of the different collections, check out this question.

like image 41
Neil Knight Avatar answered Nov 07 '22 07:11

Neil Knight