NET 2.0中Hashtable快速查找的方法
2011-05-29 11:27
232 查看
一般来说我们都是用 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();
测试结果如下:
如果不需要获得对应键的值,而是只判断的话,两种方法的区别不会很明显,大家有空可以测试下。
一般慢速的方法: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();
测试结果如下:
如果不需要获得对应键的值,而是只判断的话,两种方法的区别不会很明显,大家有空可以测试下。
相关文章推荐
- .NET 2.0中Hashtable快速查找的方法
- Hashtable快速查找的方法
- Hashtable快速查找的方法
- asp.net 2.0教程 C# 2.0匿名方法、迭代器、局部类
- 利用C#创建 IIS 站点并设置.NET Framework版本为ASP.NET 2.0 的方法(二)
- asp.NET 2.0中引发CSS失效问题原因和解决方法
- ASP.NET 2.0 中重定向的三种方法
- ASP.NET 2.0 本地化功能:本地化 Web 应用程序的新方法
- Extjs4快速查找组件的方法
- ASP.NET 2.0 网页采集方法
- Asp.net 2.0 快速入门
- NET 2.0中 新方法 -----------TryParse
- Asp.net 2.0 中将网站首页生成静态页的一个比较好的方法
- ASP.NET 2.0 实现伪静态网页方法 (转载 ————续)
- Asp.net 2.0的Eval方法详解
- 揭秘ASP.NET 2.0的Eval方法(转)
- [推荐]ASP.NET 2.0 快速入门系列课程(附代码示例)[WMV]
- ASP.NET 2.0中给DropDownList服务器控件添加项的新方法
- Asp.net 2.0在Windows 2003 Server 上配置Microsoft Excel、Microsoft Word应用程序权限时 error: 8000401a 的解决方法!
- myeclipse中快速查找类、方法