[转帖]C#中字典集合HashTable、Dictionary、ConcurrentDictionary三者区别
C#中字典集合HashTable、Dictionary、ConcurrentDictionary三者区别
https://blog.csdn.net/yinghuolsx/article/details/72952857 同事说 .net4.+ 上面的dictionary 容易出现问题 会导致应用服务器异常出现CPU100%的问题.
很重要的是这个图:

C#中HashTable、Dictionary、ConcurrentDictionar三者都表示键/值对的集合,但是到底有什么区别,下面详细介绍
一、HashTable
HashTable表示键/值对的集合。在.NET Framework中,Hashtable是System.Collections命名空间提供的一个容器,用于处理和表现类似key-value的键值对,其中key通常可用来快速查找,同时key是区分大小写;value用于存储对应于key的值。Hashtable中key-value键值对均为object类型,所以Hashtable可以支持任何类型的keyvalue键值对,任何非 null 对象都可以用作键或值。
HashTable是一种散列表,他内部维护很多对Key-Value键值对,其还有一个类似索引的值叫做散列值(HashCode),它是根据GetHashCode方法对Key通过一定算法获取得到的,所有的查找操作定位操作都是基于散列值来实现找到对应的Key和Value值的。
散列函数(GetHashCode)让散列值对应HashTable的空间地址尽量不重复。
当一个HashTable被占用一大半的时候我们通过计算散列值取得的地址值可能会重复指向同一地址,这就造成哈希冲突。
C#中键值对在HashTable中的位置Position= (HashCode& 0x7FFFFFFF) % HashTable.Length,C#是通过探测法解决哈希冲突的,当通过散列值取得的位置Postion以及被占用的时候,就会增加一个位移x值判断下一个位置Postion+x是否被占用,如果仍然被占用就继续往下位移x判断Position+2*x位置是否被占用,如果没有被占用则将值放入其中。当HashTable中的可用空间越来越小时,则获取得到可用空间的难度越来越大,消耗的时间就越多。
使用方法如下:

using System;
using System.Collections;
namespace WebApp
{
class Program
{
static void Main(string[] args)
{
Hashtable myHash=new Hashtable();
//插入
myHash.Add("1","joye.net");
myHash.Add("2", "joye.net2");
myHash.Add("3", "joye.net3");
//key 存在
try
{
myHash.Add("1", "1joye.net");
}
catch
{
Console.WriteLine("Key = \"1\" already exists.");
}
//取值
Console.WriteLine("key = \"2\", value = {0}.", myHash["2"]);
//修改
myHash["2"] = "http://www.cnblogs.com/yinrq/";
myHash["4"] = "joye.net4"; //修改的key不存在则新增
Console.WriteLine("key = \"2\", value = {0}.", myHash["2"]);
Console.WriteLine("key = \"4\", value = {0}.", myHash["4"]);
//判断key是否存在
if (!myHash.ContainsKey("5"))
{
myHash.Add("5", "joye.net5");
Console.WriteLine("key = \"5\": {0}", myHash["5"]);
}
//移除
myHash.Remove("1");
if (!myHash.ContainsKey("1"))
{
Console.WriteLine("Key \"1\" is not found.");
}
//foreach 取值
foreach (DictionaryEntry item in myHash)
{
Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
}
//所有的值
foreach (var item in myHash.Values)
{
Console.WriteLine("Value = {0}",item);
}
//所有的key
foreach (var item in myHash.Keys)
{
Console.WriteLine("Key = {0}", item);
}
Console.ReadKey();
}
}
}

结果如下:

更多参考微软官方文档:Hashtable 类
二、Dictionary
Dictionary<TKey, TValue> 泛型类提供了从一组键到一组值的映射。通过键来检索值的速度是非常快的,接近于 O(1),这是因为 Dictionary<TKey, TValue> 类是作为一个哈希表来实现的。检索速度取决于为 TKey 指定的类型的哈希算法的质量。TValue可以是值类型,数组,类或其他。
Dictionary是一种变种的HashTable,它采用一种分离链接散列表的数据结构来解决哈希冲突的问题。
简单使用代码:

using System;
using System.Collections;
using System.Collections.Generic;
namespace WebApp
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> myDic = new Dictionary<string, string>();
//插入
myDic.Add("1", "joye.net");
myDic.Add("2", "joye.net2");
myDic.Add("3", "joye.net3");
//key 存在
try
{
myDic.Add("1", "1joye.net");
}
catch
{
Console.WriteLine("Key = \"1\" already exists.");
}
//取值
Console.WriteLine("key = \"2\", value = {0}.", myDic["2"]);
//修改
myDic["2"] = "http://www.cnblogs.com/yinrq/";
myDic["4"] = "joye.net4"; //修改的key不存在则新增
Console.WriteLine("key = \"2\", value = {0}.", myDic["2"]);
Console.WriteLine("key = \"4\", value = {0}.", myDic["4"]);
//判断key是否存在
if (!myDic.ContainsKey("5"))
{
myDic.Add("5", "joye.net5");
Console.WriteLine("key = \"5\": {0}", myDic["5"]);
}
//移除
myDic.Remove("1");
if (!myDic.ContainsKey("1"))
{
Console.WriteLine("Key \"1\" is not found.");
}
//foreach 取值
foreach (var item in myDic)
{
Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
}
//所有的值
foreach (var item in myDic.Values)
{
Console.WriteLine("Value = {0}",item);
}
//所有的key
foreach (var item in myDic.Keys)
{
Console.WriteLine("Key = {0}", item);
}
Console.ReadKey();
}
}
}

运行结果:

更多资料参考:Dictionary 类
三、ConcurrentDictionary
表示可由多个线程同时访问的键/值对的线程安全集合。
ConcurrentDictionary<TKey, TValue> framework4出现的,可由多个线程同时访问,且线程安全。用法同Dictionary很多相同,但是多了一些方法。ConcurrentDictionary 属于System.Collections.Concurrent 命名空间按照MSDN上所说:
System.Collections.Concurrent 命名空间提供多个线程安全集合类。当有多个线程并发访问集合时,应使用这些类代替 System.Collections 和 System.Collections.Generic 命名空间中的对应类型。
更多资料:ConcurrentDictionary<TKey,?TValue> 类
四、对比总结
分别插入500万条数据,然后遍历,看看耗时。

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
namespace WebApp
{
class Program
{
static Hashtable _hashtable;
static Dictionary<string, string> _dictionary;
static ConcurrentDictionary<string, string> _conDictionary;
static void Main(string[] args)
{
Compare(5000000);
Console.ReadLine();
Console.Read();
}
public static void Compare(int dataCount)
{
_hashtable = new Hashtable();
_dictionary = new Dictionary<string, string>();
_conDictionary=new ConcurrentDictionary<string, string>();
Stopwatch stopWatch = new Stopwatch();
// Hashtable
stopWatch.Start();
for (int i = 0; i < dataCount; i++)
{
_hashtable.Add("key" + i.ToString(), "Value" + i.ToString());
}
stopWatch.Stop();
Console.WriteLine("HashTable插" + dataCount + "条耗时(毫秒):" + stopWatch.ElapsedMilliseconds);
//Dictionary
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < dataCount; i++)
{
_dictionary.Add("key" + i.ToString(), "Value" +i.ToString());
}
stopWatch.Stop();
Console.WriteLine("Dictionary插" + dataCount + "条耗时(毫秒):" + stopWatch.ElapsedMilliseconds);
//ConcurrentDictionary
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < dataCount; i++)
{
_conDictionary.TryAdd("key" + i.ToString(), "Value" + i.ToString());
}
stopWatch.Stop();
Console.WriteLine("ConcurrentDictionary插" + dataCount + "条耗时(毫秒):" + stopWatch.ElapsedMilliseconds);
// Hashtable
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < _hashtable.Count; i++)
{
var key = _hashtable[i];
}
stopWatch.Stop();
Console.WriteLine("HashTable遍历时间(毫秒):" + stopWatch.ElapsedMilliseconds);
//Dictionary
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < _hashtable.Count; i++)
{
var key = _dictionary["key" + i.ToString()];
}
stopWatch.Stop();
Console.WriteLine("Dictionary遍历时间(毫秒):" + stopWatch.ElapsedMilliseconds);
//ConcurrentDictionary
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < _hashtable.Count; i++)
{
var key = _conDictionary["key"+i.ToString()];
}
stopWatch.Stop();
Console.WriteLine("ConcurrentDictionary遍历时间(毫秒):" + stopWatch.ElapsedMilliseconds);
}
}
}

运行结果:

可以看出:
大数据插入Dictionary花费时间最少
遍历HashTable最快是Dictionary的1/5,ConcurrentDictionary的1/10
单线程建议用Dictionary,多线程建议用ConcurrentDictionary或者HashTable(Hashtable tab = Hashtable.Synchronized(new Hashtable());获得线程安全的对象)
[转帖]C#中字典集合HashTable、Dictionary、ConcurrentDictionary三者区别的更多相关文章
- C#中字典集合HashTable、Dictionary、ConcurrentDictionary三者区别
C#中HashTable.Dictionary.ConcurrentDictionar三者都表示键/值对的集合,但是到底有什么区别,下面详细介绍 一.HashTable HashTable表示键/值对 ...
- 集合Hashtable Dictionary Hashset
#region Dictionary<K,V> Dictionary<string, Person> dict = new Dictionary<string, Pers ...
- .net框架-字典对象 Hashtable & Dictionary<TKey,TValue> & SortedList
字典对象: 字典对象是表示键值对的集合 字典对象有Hashtable(.net 1.0)及其泛型版本Dictionary<TKey,TValue> 字典对象还包括SortedList及其泛 ...
- repeater绑定数组、哈希表、字典 ArrayList/HashTable,Dictionary为datasource
原文发布时间为:2009-11-19 -- 来源于本人的百度文章 [由搬家工具导入] repeater绑定数组、哈希表、字典datasource为ArrayList/HashTable,Diction ...
- [转载]C#中字典集合的两种遍历
Dictionary<string, string> dictionary = new Dictionary<string,string>(); foreach (string ...
- HashTable、Dictionary、ConcurrentDictionary三者区别
转载自https://blog.csdn.net/yinghuolsx/article/details/72952857 1.HashTable HashTable表示键/值对的集合.在.NET Fr ...
- java中hashmap和hashtable和hashset的区别
hastTable和hashMap的区别:(1)Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实现.(2)这个不同即是最重要的一点:Ha ...
- java中HashMap、HashTable、TreeMap的区别总结【表格对比清楚明了】
底层 有序否 键值对能否为Null 遍历 线程安全 哈希Code Hashmap 数组+链表 无序 都可null iterator 不安全 内部hash方法 Hashtable 数组+链表 无序 ...
- Python中字典和集合
Python中字典和集合 映射类型: 表示一个任意对象的集合,且可以通过另一个几乎是任意键值的集合进行索引 与序列不同,映射是无序的,通过键进行索引 任何不可变对象都可用作字典的键,如字符串.数字.元 ...
随机推荐
- 【leetcode】1248. Count Number of Nice Subarrays
题目如下: Given an array of integers nums and an integer k. A subarray is called nice if there are k odd ...
- 对JS继承的研究--------------引用
问:类继承和原型继承不是同一回事儿吗,只是风格选择而已? 答:不是! 类继承和原型继承不论从本质上还是从语法上来说,都是两个截然不同的概念. 二者之间有着区分彼此的本质性特征.要完全看懂本文,你必须牢 ...
- CSS样式,语法,添加方法,文本,字体
总结一些css的基础知识 ㈠css样式 css:cascading style sheets 层叠样式表 css内容和样式相分离,便于修改样式. ㈡css语法 ㈢css添加方法 ⑴行内添加:放在&l ...
- Akka 介绍
欢迎使用 Akka,Akka 是一套被用来在在多处理器核心和网络之间被设计可扩展和具有相关弹性的开源工具集.Akka 允许你更加关注商业需求而不是书写低级别的代码来提供可靠性,容错率和高性能. 很多常 ...
- 51 Nod 1556计算(默慈金数的应用)
#include<bits/stdc++.h> #define mod 1000000007 using namespace std; typedef long long ll; ll m ...
- 【IOI2018】组合动作
还是自己水平不够,想了两天没想出来--(然后我就被其他人吊打了) 这种题目看了题解就秒会,自己想就想不出来-- 下面是我的心路历程(我就在想出来又叉掉的不断循环中度过--) 开始把题目看成了查询限制 ...
- Linux命令-文件传输
Linux命令-文件传输 Linux lprm命令 Linux lprm命令用于将一个工作由打印机贮列中移除 尚未完成的打印机工作会被放在打印机贮列之中,这个命令可用来将常未送到打印机的工作取消.由于 ...
- 工具类--BeanUtils----Bean转换工具
package com.zhouyy.netBank.util; import java.beans.PropertyDescriptor; import java.lang.reflect.Fiel ...
- idea为项目添加ignore文件忽略unversion的文件
最近初学Git,而且在使用的IDE是IntelliJ IDEA,发现IDEA在提交项目到本地仓库的时候,会把.idea文件夹中的内容也提交上去,这里面放的是一些项目的配置信息,包括历史记录,版本控制信 ...
- sql server中 设置与查看锁的超时时间(ZT) @@LOCK_TIMEOUT
在数据库的应用系统中,死锁是不可避免的.通过设置死锁的处理优先级方法,可以在数据库引擎中自动检测到死锁,对发生的死锁会话进行干预,从而达到解除死锁的目点,但在这种情况下,会话只能被动的等待数据库引 ...