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

ASP.NET
关于.NET动态代理的介绍和应用简介
ASP.NET2.0服务器控件之类型转换器
ASP.net做的IP访问限制
Asp.Net2.0权限树中Checkbox的操作
ASP.NET数据库编程之Access连接失败
ASP.NET 2005 Treeview终极解决方案
ASP.NET数据库编程之处理文件访问许可
ASP.NET 2.0中的页面输出缓存
ASP.NET 2.0服务器控件开发之复杂属性
ASP.NET2.0中数据源控件之异步数据访问
將datagrid控件內容輸出到excel文件
ASP.NET技巧:教你制做Web实时进度条
实现基于事件通知的.Net套接字
ASP.NET技巧:同时对多个文件进行大量写操作对性能优化
ASP.NET中根据XML动态创建使用WEB组件
QQ关于.net的精彩对话
ASP.NET技巧:access下的分页方案
为自己的ASP网站系统构建一套标记语言
Visual Studio.Net 内幕(6)
Asp.Net中NHiernate的Session的管理

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 98 ::
收藏到网摘: 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();