Guillermo G. Blog

Software Architect
ASP.NET MCP
"The best way to predict the future is to invent it"

Tip: Hashtable vs SortedList

I wrote this short tip based in a question made from a workmate about a functionality that he wanted that appears in a Hashtable class.

Remember that a Hashtable represents a collection of key/value pairs that are organized based on the hash code of the key, and when a element is added to the Hashtable it's stored based on the hash code of the key, and the elements don't preserves the order based in their insertion to the Hashtable's "bag". If I want to retrieve the elements in the same order that they were placed, there's no way to retrieve them (normally).

And, if I want a collection class which can add key/value elements, and it maintains all the items sorted based in the insertion order? This class exists and their name is SortedList.

A SortedList is a collection of key/value pairs that is sorted by the keys and are accessible by key and by index.

If you want that the items contained in a collection always be "sorted" you need to use a SortedList instead a HashTable. If you don need the items sorted then use a HashTable, beacuse it's more faster than a SortedList obtaining a value from their "bag".

Updated 01-08-2008
An interesting performance test to compare four different implementations of the IDictionary interface posted by Vladimir Bodurov (IDictionary options - performance test - SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable).

Comments

Ricardo said:

But when is more convenient use one of the other?

I read that Hashtables perform better when need to find elements in big sets of data otherwise is more efficient in time to do simple binary search.

# May 29, 2008 11:35 AM

gugonzar said:

Hi Ricardo, You're right!

You can find a performance test realized by Vladimir Bodurov with great details... blog.bodurov.com/Post.aspx

# August 1, 2008 11:12 AM

Sanjay Bhujbal said:

In Hashtable data is stored in sorted format based on the key hashcode and in SortedList it is based on the only key.

In hashtable data is stored in object format but in sortedlist we can use generics so it contais strongly typed data.

So while serching values there is no boxing and unboxing operation performed in sortedlist so the performance of sortedlist is better than Hashtable.

Do you agree with my statements?

# October 19, 2008 7:13 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)