利用 Hashtable 实现快速查找比较-实例

作者:vkvi 来源:ITPOW(原创) 日期:2008-3-27

以下示例比较了利用 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;
            }
        }

结果

Hashtable 查找比较

相关阅读

相关文章