HashTable遍历效率比较
一、什么是Hashtable
Hashtable 类代表了一系列基于键的哈希代码组织起来的键/值对。它使用键来访问集合中的元素。
二、4种遍历方法
HashTable 遍历的时候,有4种方法
- Method1: 通过foreach遍历哈希表中的键;
- Method2: 通过foreach遍历哈希表中的值;
- Method3: DictionaryEntry 遍历哈希表中的键值;
- Method4:IDictionaryEnumerator 遍历哈希表中的键值;
三、测试
生成1千万条hashtable数据进行比对:
static void Main(string[] args)
{
//--------产生1000W条HashTable记录-------------------
Hashtable hashtable = new Hashtable();
for (int i = 0; i < 10000000; i++)
{
hashtable.Add(i.ToString(), "qcj");
}
Console.WriteLine("Ready? Let's Go!");
Console.WriteLine(" ");
Stopwatch watch = new Stopwatch();
//遍历方法一:遍历哈希表中的键--------------------
watch.Start();
foreach (string key in hashtable.Keys)
{
//Console.WriteLine(string.Format("{0}-{1}"), key, hashtable[key]);
}
watch.Stop();
Console.WriteLine("foreach遍历键:" + watch.Elapsed.TotalSeconds);
Console.WriteLine("**********************************************************");
//遍历方法二:遍历哈希表中的值----------------------
watch.Restart();
foreach (string value in hashtable.Values)
{
// Console.WriteLine(value);
}
watch.Stop();
Console.WriteLine("foreach遍历值:" + watch.Elapsed.TotalSeconds);
Console.WriteLine("**********************************************************");
//遍历方法三:遍历哈希表中的键值-------------------
watch.Restart();
foreach (DictionaryEntry de in hashtable)
{
// Console.WriteLine(string.Format("{0}-{1}", de.Key, de.Value));
}
watch.Stop();
Console.WriteLine("DictionaryEntry 遍历键值:" + watch.Elapsed.TotalSeconds);
Console.WriteLine("**********************************************************");
//遍历方法四:遍历哈希表中的键值------------------------
watch.Restart();
IDictionaryEnumerator myEnumerator = hashtable.GetEnumerator();
bool flag = myEnumerator.MoveNext();
while (flag)
{
//Console.WriteLine(myEnumerator.Key + "-" + myEnumerator.Value);
flag = myEnumerator.MoveNext();
}
watch.Stop();
Console.WriteLine("IDictionaryEnumerator 遍历键值:" + watch.Elapsed.TotalSeconds);
Console.Read();
}
最后结果如下:
四、结果
结果表明:
-
foreach遍历值和IDictionaryEnumerator遍历键值速度差不多
-
IDictionaryEnumerator要更快一点,而且能同时获得key 和 value
-
foreach遍历值的时候访问不到键,遍历键的时候访问不到值。