以下示例比较了利用 Hashtable 和数组进行查找的效率。
int count = 1000000; // 总共有多少个键
int key = 999999; // 要查找的键位置
System.Collections.Hashtable hastable = new System.Collections.Hashtable();
int[] array = new int[count];
for (int i = 0; i < count; i++)
{
hastable.Add(i, i);
array[i] = i;
}
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); //计时器
_result.Text = "";
//在 hashtable 中查找,方法一
stopwatch.Reset();
stopwatch.Start();
object n = hastable[key];
if (n != null)
{
stopwatch.Stop();
_result.Text += "<p>Hashtable 法一用时:" + stopwatch.ElapsedTicks + "。</p>";
}
//在 hashtable 中查找,方法二
stopwatch.Reset();
stopwatch.Start();
if (hastable.ContainsKey(key))
{
stopwatch.Stop();
_result.Text += "<p>Hashtable 法二用时:" + stopwatch.ElapsedTicks + "。</p>";
}
//在数组中查找
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < array.Length; i++)
{
if (array[i] == key)
{
stopwatch.Stop();
_result.Text += "<p>Array 用时:" + stopwatch.ElapsedTicks + "。</p>";
break;
}
}
结果

相关阅读