快速查找Hashtable中的元素

Hashtable几一种键值对应的对象集合,查找Hashtable的元素是其应用的一个很重要方面,本文介绍一种快速查找的方法,思路是:直接读取键值然后判断这个对象是否为 null 然后读取。

先看以下二个例子代码,第一个是我们平时用的最多的查找方法,第二个就是本文要讲的快速查找方法:

  1. 一般慢速的方法:if (objHash.ContainsKey(keyValue))
    {
        strValue=(String)objHash[keyValue]; 
    }
  2. 而快速的方法是:Object objValue=objHash[keyValue];
    if (objValue!=null)
    {
        strValue=(String)objValue;
    }

两种方法的速度经过测试能差一倍左右。下面是测试代码:
Hashtable objHash = new Hashtable();
for (Int32 intI = 0; intI < 1000; intI++)
{
    objHash.Add("Key_" + intI.ToString(), "Value_" + intI.ToString());
}
String strValue = String.Empty;
Stopwatch timer = new Stopwatch();
timer.Start();
for (Int32 intI = 0; intI < 1000; intI++)
{
    Object objValue = objHash["Key_" + intI.ToString()];
    if (objValue != null)
    {
        strValue = (String)objValue;
    }
}
timer.Stop();
Console.WriteLine("Execution time was {0:F1} microseconds.", timer.Elapsed.Ticks / 10m);
timer.Reset();
timer.Start();
for (Int32 intI = 0; intI < 1000; intI++)
{
    if (objHash.ContainsKey("Key_" + intI.ToString()))
    {
        strValue = (String)objHash["Key_" + intI.ToString()];
    }
}
timer.Stop();
Console.WriteLine("Execution time was {0:F1} microseconds.", timer.Elapsed.Ticks / 10m);
timer.Reset();

测试结果如下:

如果不需要获得对应键的值,而是只判断的话,两种方法的区别不会很明显,大家有空可以测试下。

程序的效率有时都是小细节上体现出来.

文章转自网站制作教程网,详细地址:http://www.web2bar.cn/Article/3049.aspx

posted on 2008-12-01 19:27  爱问天  阅读(284)  评论(0编辑  收藏  举报