当前位置导航:炫浪网>>网络学院>>网页制作>>ASP.NET教程

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

        一般来说我们都是用 Hashtable 的 ContainsKey 方法来查找 Hashtable 中是否存在某个键值然后读取他,但是这个方法并不是效率最好的方法。比较好的方法是直接读取键值然后判断这个对象是否为 null 然后读取。两种代码分别如下:

一般慢速的方法:if (objHash.ContainsKey(keyValue))
{
    strValue=(String)objHash[keyValue];
}
而快速的方法是: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();

测试结果如下:

如果不需要获得对应键的值,而是只判断的话,

共2页 首页 上一页 1 2 下一页 尾页 跳转到
相关内容
赞助商链接