blah blah blah is here! blah blah » Close

up1down
link

Which is faster? Why, and if not in every situation when? Which do you prefer? Which is simpler? For my purposes performance is a huge factor, so performance > simplicity.

last answered 6 months ago

1 answers

link

If either the key, value or both are value types, then a generic Dictionary is faster than a Hashtable.

This is because a Hashtable stores everything internally as object references and value types therefore need to be boxed when they are stored and unboxed when they are retrieved which is an expensive operation, performance wise.

There's no boxing with a Dictionary which is strongly typed and stores both the key and value as their actual types.

If the key and value are reference types, there's little or no difference in performance between the two classes. Any difference there may be is accounted for by a technical difference in the way they resolve collisions - the Dictionary uses chaining and the Hashtable uses rehashing.

Personally, I always use the generic Dictionary nowadays because (as mentioned already) it's strongly typed, there's never any boxing and when you retrieve a value, you never need to cast it to its actual type.

Feedback