Dictionary<T1,T2>和Hashtable的异同

来源:互联网 发布:拉瑞 威廉姆斯 知乎 编辑:程序博客网 时间:2024/04/30 12:13
Dictionary<int, int> dic = new Dictionary<int, int>();            dic.Add(1, 5);            dic.Add(10, 3);            dic.Add(2, 5);            foreach (int key in dic.Keys)            {                Console.WriteLine(key);            }            Hashtable hashtable = new Hashtable();            hashtable.Add(1, 5);            hashtable.Add(10, 3);            hashtable.Add(2, 5);            foreach (object key in hashtable.Keys)            {                Console.WriteLine(key.ToString());            }

Dictionary<T1,T2>是根据插入的顺序来遍历,但是Hashtable在插入时会打乱其位置。在反编译这段源码时在http://www.cnblogs.com/kym/archive/2009/12/31/1636768.html  还提到HashTable的线程是安全的,不过现在我还不理解这个就不写啦。

Dictionary<T1,T2>的存储原理:

根据Key通过Hash计算来得到其应存放的虚拟内存地址,当按照Key进行查找时,根据Key计算出其所存放的虚拟内存地址,去对应的内存地址找数据,得到其Value。这一点HashTable与其相同

 

遍历时DictionaryList的效率:

Dictionary<string, string> dic = new Dictionary<string, string>();            Random random = new Random();            for (int i = 0; i < 100000; i++)            {                int r = random.Next(10);                dic.Add(i.ToString(), r.ToString());            }            StringBuilder sb1 = new StringBuilder();            Stopwatch sp1 = new Stopwatch();            sp1.Start();            foreach (string item in dic.Keys)            {                sb1.Append(dic[item]);            }            sp1.Stop();            Response.Write("dic花费的时间:" + sp1.ElapsedTicks.ToString());            List<string> list = new List<string>();            for (int i = 0; i < 100000; i++)            {                list.Add(random.Next().ToString());            }            sb1 = new StringBuilder(10000000);            sp1.Reset();            sp1.Start();            foreach (string s in list)            {                sb1.Append(s);            }            sp1.Stop();            Response.Write("List花费的时间:" + sp1.ElapsedTicks.ToString());

结果:

List<T>是对数组做了一层包装,在数据结构上称之为线性表,而线性表的概念是,在内存中的连续区域,除了首节点和尾节点外,每个节点都有着其唯一的前驱结点和后续节点。HashTable或者Dictionary,他是根据Key而根据Hash算法分析产生的内存地址,因此在宏观上是不连续的,虽然微软对其算法也进行了很大的优化。

由于这样的不连续,在遍历时,Dictionary必然会产生大量的内存换页操作,而List只需要进行最少的内存换页即可



0 0