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

ASP.NET
ASP.NET编程中的十大技巧
ASP.NET常用函数(推荐)
ASP.NET上传图片并生成可带版权信息的缩略图
用javascript打造搜索工具栏
ASP.NET中动态控制RDLC报表
用ASP.NET还原与恢复Sql server
在ASP.NET里得到网站的域名
Asp.net中的mail的发送
用ASP.Net实现文件的在线压缩和解压缩
ASP.NET中文件上传下载方法集合
ASP.NET通过Remoting service上传文件
ASP.NET2.0服务器控件之Render方法
ASP.NET2.0新特性概述
asp.net2.0如何加密数据库联接字符串
用.NET 2.0压缩/解压功能处理大型数据
ASP.NET入门随想之检票的老太太
ASP与ASP.NET互通COOKIES的一点经验
ASP.NET2.0数据库入门之SqlDataSource
ASP.NET2.0数据库入门之SQL Server
ASP.NET 2.0下的条件编译

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


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