Faster Hashtable lookups in .NET

Hashtables are very convenient data structures however they are not very fast and it is very easy to make them even slower by using more logical, but ultimately much slower approach, consider the code below:

Hashtable oHash=new Hashtable();  
string sKey="key";
oHash[sKey]="value";
string sValue="";
// slow! 
if(oHash.Contains(sKey))
sValue=(string)oHash[sKey];

// clear up value
sValue="";
// much faster
object oValue=oHash[sKey];  
if(oValue!=null)
sValue=(string)oValue;

The difference in performance is about 2 times: the reason is that checking whether a hashtable contains an item actually has the same or almost the same cost as retrieving value from it or getting null if it is not present: this would not work if possible value of a key can actually be null, but in many cases using faster version will improve performance nicely, so long as you are not bottlenecked elsewhere!

3 Responses to “Faster Hashtable lookups in .NET”

  1. DimPrawn Says:

    // much faster
    object oValue=oHash[sKey]; if(oValue!=null)
    sValue=(string)oValue;

    sValue = oHash[sKey] as string;

    is easier on the eye and doesn’t require the object variable and automatically casts the object to a string if it can.

  2. alexc Says:

    Yes, that is definately better and it does not fail in case oHash[sKey] being null, unlike casting (string), which is why I always checked for null, good one! :)

  3. alexc Says:

    It should be mentioned that the above “as” casting approach won’t work when dealing with non-nullable types like int/long etc, so it can’t be used in all cases.

Leave a Reply