当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > .NET 2.0中Hashtable快速查找的方法

ASP.NET
Visual Studio.Net 内幕(7)
.Net 2.0 原汁原味读取注册表
ASP.NET 2.0中预设的cookie
ASP.NET:一段比较经典的多线程学习代码
ASP.NET2.0服务器控件之自定义状态管理
Asp.net给站点某目录增加Aspnet用户
ASP.NET技巧:请求网址并解析返回的html
在Asp.net用C#建立动态Excel
ASP.NET2.0:页面中链入的CSS、js文件带中文时需注意
ASP.NET技巧:数据岛出到Excel最为简易的方法
第一次用.net2.0 LOGIN登陆控件的困惑和解决方法
在ASP.net中保存/取出图片入/从SQL数据库
ASP.NET技巧:做个DataList可分页的数据源
在.NET中利用委托实现窗体间通信
在.NET2.0中使用自定义事务操作
解决 ASP.NET中目录访问权限的问题
ASP.Net防止刷新自动触发事件的解决方案
白刃之战:PHP vs. ASP.NET(节选)-架构比较
C#中使用SendMessage
提取HTML代码中文字的C#函数

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 100 ::
收藏到网摘: n/a

一般来说我们都是用 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();