.NET 2.0中Hashtable快速查找的方法


一般来说我们都是用 Hashtable 的 ContainsKey 方法来查找 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();

测试结果如下:

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


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3