您的位置:首页 > 其它

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

2009-03-23 22:40 423 查看
一般来说我们都是用 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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: