欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

c# Dictionary泛型和Hashtable性能对比

程序员文章站 2022-03-21 16:29:06
...

测试代码

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
相关标签: c#