views:

200

answers:

2

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?

+1  A: 

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> and SortedList<TKey, TValue>. Of course, I would be inclined to guess that Dictionary<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 HashTable in at least one sense: they do not require boxing/unboxing of keys and values as System.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 a ReaderWriterLock or ReaderWriterLockSlim (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 a HashTable.

Dan Tao
HashSet<TKey, TValue> would perhaps be good to be considered, I guess.
Will Marcouiller
@Will: You may be thinking of a different class? A `HashSet<T>` is a collection of unique values; it does not provide key-value pairing.
Dan Tao
Duh! You're right! I must have gotten confused with a Dictionary<TKey, HashSet<T>>... Sorry! =(
Will Marcouiller
@Will: Huh... I like that. Actually I feel like a `Dictionary<string, HashSet<string>>` might actually be the appropriate storage structure for an *actual* dictionary (you know, like Webster's, with multiple definitions for each word).
Dan Tao
@Dan: That's good! Indeed this structure would allow one to search for a word and then get the resulting definitions for this word. Sounds great! I guess I'll remember the idea and apply it when it is appropriate. I have seen such code in the LINQ to AD sample code by Bart de Smet, from Microsoft. He uses it to keep track of property changes.
Will Marcouiller
Thanks to all :)
salman