您的位置:首页 > 其它

Faster Hashtable lookups in .NET

2007-03-06 10:13 197 查看
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!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: