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与其相同
遍历时Dictionary和List的效率:
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
- Dictionary<T1,T2>和Hashtable的异同
- Hashtable与Dictionary的异同
- 浅谈Hashtable与Dictionary的异同
- 磁共振中的T1, T2 和 T2*的原理和区别
- Hashtable和dictionary的区别
- [c#基础知识]浅谈Hashtable与Dictionary的异同
- HashMap和Hashtable的异同
- Hashtable和HashMap的异同
- 对复杂字典Dictionary<T1,T2>排序问题
- Dictionary<K,V>和HashTable的区别
- HashTable和泛型Dictionary的使用
- Dictionary<K,V>和HashTable的区别
- C# hashTable 和 Dictionary的区别。
- HashTable、HashSet和Dictionary的区别
- 遍历Dictionary和HashTable的方法
- HashTable、HashSet和Dictionary的区别
- HashTable、HashSet和Dictionary的区别
- C# HashTable、HashSet和Dictionary的区别
- NSString的内存管理问题
- ASP.NET 应用程序生命周期和ASP.NET 页生命周期
- What is the difference between a soft reference and a weak reference in Java?
- 【状态压缩DP】[APIO2007]动物园
- 常用ASCII码详细对照表
- Dictionary<T1,T2>和Hashtable的异同
- jquery 动态的添加数据,获取动态的数据
- 获取当前访问的路径
- android 系统亮度设置
- Decoda1.17编译实录
- Ubuntu12.04 安装sqlite
- TCP/IP详解卷1 读书笔记:第一章 概述
- hive与derby的安装
- 蝉游记 通过微博冷启动