Translate Into English Coffee & Tea
ASP.NET 中的 AJAX ASP.NET 画图全接触 ASP.NET 与 XML 声明式数据绑定 ASP.NET 网页抓取
C# 基础 C# 类教程 C# 加密 ASP.NET 成员资格 非“自动化”处理 Excel
QuickAjax Ajax 完美的语法高亮器 Silverlight Popfly
通栏广告
利用 Hashtable 实现快速查找比较-实例

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

相关阅读

文章评论
标题:必填
内容:
文章信息