五、用泛型副本替換雜湊表

來源:互聯網
上載者:User
問題:

你想通過用Hashtable對象的泛型表示來提高你的應用程式的效能。當你發現,結構體或其他資料類型在被儲存到Hashtable中時都會發生裝箱/拆箱操作時,這是非常急需的。

解決方案:

用更快的泛型類System.Collections.Generic.Dictionary替換所有出現System.Collections.Hashtable類的地方。

下面是一個簡單的使用System.Collections.Hashtable對象的樣本:

    public static void UseNonGenericHashtable()
    { 
        // 建立並相似一個Hashtable.
        Hashtable numbers = new Hashtable(); 
        numbers.Add(1, "one");    // 發生裝箱操作
        numbers.Add(2, "two");    // 發生裝箱操作

        // 顯示Hashtable中所有的索引值對
        // 在每一個遞迴中都會發生一次拆箱操作
        foreach (DictionaryEntry de in numbers)
        {
            Console.WriteLine("Key: " + de.Key + "\tValue: " + de.Value); 
        }

        numbers.Clear();
    }

下面是一個使用System.Collections.Generic.Dictionary<T,U>對象的相似的代碼:

    public static void UseGenericDictionary()
    {
        // 建立並顯示一個Dictionary.
        Dictionary<int, string> numbers = new Dictionary<int, string>();
        numbers.Add(1, "one");
        numbers.Add(2, "two");

        // 顯示所有Dictionary中的索引值對
        foreach (KeyValuePair<int, string> kvp in numbers)
        {
            Console.WriteLine("Key: " + kvp.Key + "\tValue: " + kvp.Value); 
        }

        numbers.Clear();
    }

討論:

在你的應用程式中,對於Hashtable的簡單實現,這個替換應該是非常簡單的。但是,有一些事是需要密切關注的。例如,Dictionary類沒有實現ICloneable介面,而Hashtable類實現了。所以,各位在使用的時候還是需要根據自己的實際情況做相應的改變。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.