Valentin Valentin - 9 months ago 73
C# Question

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?

Answer Source

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.