Faster Hashtable lookups in .NET

I almost forget where  the original source is from.

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!

你可能感兴趣的:(Hashtable)