Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Array or Dictionary?

I wanted to know is C# array has a constant access speed?
I need to store 1000 items in static array, that will be initialized during server startup. This array will be used readonly, so there will be no changes to array.
Should I use a simple C# array (new MyClass[]) or Dictionary instead.

I am really new to C# and trying to understand how C# arrays access works.
Can they be compared to c++ arrays by speed?

like image 915
Valentin Avatar asked Mar 15 '10 17:03

Valentin


3 Answers

Yes, if you know the index the speed is constant O(1), much like a lookup in a hashtable backed dictionary (e.g. Dictionary<>).

If the index is not known then you will have to perform a search (linear if the items are unsorted O(n) or binary if they are O(log n)).

That said, in real terms the array lookup will be quicker because a hashtable lookup is two operations: calculate the hash of the key to get an index and retrieve the value from an internal array at that index.

Also note that a if the hashcode of the key is badly implemented, the hashtable's magical properties quickly evaporate and, in the worst case (where every key has the same hashcode) you will end up with an elaborate linked-list in which every look up will be a linear search at a cost of O(n). Double check those hashcodes!

like image 34
Paul Ruane Avatar answered Nov 19 '22 07:11

Paul Ruane


The best choice depends on how you need to access the elements.

If you want to access them by index, then use an Array. Arrays in C# have constant access speed, and are very similar to a C++ array in terms of speed for access.

Dictionaries, however, have very fast access (the Item property approaches O(1) access time, but depends on how good of an implementation the stored key has for GetHashCode). If you need to lookup your items based on a key value and not by index, then dictionary would be appropriate instead.

like image 168
Reed Copsey Avatar answered Nov 19 '22 07:11

Reed Copsey


It depends on the way you are going to get elements from the array. If you are going to get elements by positions (index) in the array then array will be quicker (or at least not slower than dictionary). If you are going to search for elements in the array than dictionary will be faster.

like image 2
Andrew Bezzub Avatar answered Nov 19 '22 05:11

Andrew Bezzub