c# Dictionary泛型和Hashtable性能對比

測試代碼

using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System;
using DataStructure;
using DataStructure.Toolkit;

namespace Test
{
    public class TestNormalAndGenericCollection
    {
        void T1()
        {
            var cnt = 100000;
            var dic = new Dictionary<int, string>();
            Printer.LogDuration(() =>
            {
                for (var i = 0; i < cnt; i++)
                {
                    dic.Add(i, i.ToString());
                }
            });

            Printer.LogDuration(() =>
            {
                for (var i = 0; i < cnt; i++)
                {
                    var s = dic[i];
                }
            });
        }

        void T2()
        {
            var cnt = 100000;
            var dic = new Hashtable();
            Printer.LogDuration(() =>
            {
                for (var i = 0; i < cnt; i++)
                {
                    dic.Add(i, i.ToString());
                }
            });

            Printer.LogDuration(() =>
            {
                for (var i = 0; i < cnt; i++)
                {
                    var s = dic[i];
                }
            });
        }

        public void Test()
        {
            T1();
            T2();
        }
    }
}

測試結果

----------------------- time tick start -----------------------
100006 = 637130455113074868 - 637130455112974862----------------------- time tick end -----------------------
----------------------- time tick start -----------------------
20001 = 637130455113094869 - 637130455113074868----------------------- time tick end -----------------------
----------------------- time tick start -----------------------
150008 = 637130455113244877 - 637130455113094869----------------------- time tick end -----------------------
----------------------- time tick start -----------------------
40003 = 637130455113284880 - 637130455113244877----------------------- time tick end -----------------------

結論

  • Dictionary<TKey,TVal>的存取性能都好於Hashtable
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章