Which one of the C# <Key, Value> structure implementations has better performance and higher speed?
P.S.1: I Have two thread, one of them writes into collection, and another one reads and writes into it.
P.S.2: Key items are random numbers, and then my access is random. Write and read actions are simultaneous.
I am using hashtable, but I want to know is there any better implementation with less resource usage and better performance?
For profiling yourself, there are many options. One free profiler I’ve used and which I would recommend is EQATEC. There are plenty more to choose from, many of which are referenced in this SO question.
As for implementations, the first few that pop into mind are
Dictionary<TKey, TValue>,SortedDictionary<TKey, TValue>andSortedList<TKey, TValue>. Of course, I would be inclined to guess thatDictionary<TKey, TValue>is the fastest since it’s the simplest in terms of features. But I haven’t ever tested them against one another for speed.Note that the above classes are all generic, which should make them more efficient than
HashTablein at least one sense: they do not require boxing/unboxing of keys and values asSystem.Object, which results in unnecessary memory allocation.Something else to be aware of is that since you’re in a multithreaded scenario, you’ll need to take care to lock your reads/writes somehow. (The above classes, unlike
HashTable, are not guaranteed to be thread-safe for multiple readers and a writer.) Locking on a common object may be your best bet in most cases, whereas if you’re performing more reads than writes you might want to consider using aReaderWriterLockorReaderWriterLockSlim(both of which permit switching between multiple simultaneous readers and a single writer). If you are enumerating over the collection then you should really be locking anyway–even with aHashTable.