Hashtable 和 Dictionary 存储的都是键值对,我的理解是Dictionary是Hashtable的泛型实现。

Hashtable的键和值都是object类型。所以,key和value 都可以是不同类型的值。当把变量定义成Dictionary<object, object> dic时,表现上就和Hashtable一样了。

class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
Dictionary<object, object> dic = new Dictionary<object, object>(); TestClass tc1 = new TestClass();
TestClass tc2 = new TestClass(); ht.Add(tc1, tc1);
ht.Add("key2", "htv2");
dic.Add(tc1, tc1);
dic.Add("key2", "dicv2");
Console.WriteLine(ht[tc1] + " " + ht["key2"]);
Console.WriteLine(dic[tc1] + " " + dic["key2"]);
Console.ReadLine();
} class TestClass
{
public int x;
public int y;
}
}

输出如下:

接下来比较一下性能方面:

首先测试 key和value都是整型的情况:

static void Main(string[] args)
{
Hashtable ht = new Hashtable();
Dictionary<object, object> dic = new Dictionary<object, object>();
//Dictionary<object, int> dic = new Dictionary<object, int>();
//Dictionary<int, int> dic = new Dictionary<int, int>();
Stopwatch sw = new Stopwatch();
int count = ; sw.Start();
for (int i = ; i < count; i++)
{
ht.Add(i, i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
//sw.Start();
//for (int i = 0; i < count; i++)
//{
// dic.Add(i, i);
//}
//sw.Stop();
//Console.WriteLine(sw.ElapsedMilliseconds); Console.ReadLine();
}

开始我是两段一起测的,后来我对换两个for循环代码块发现测试先后顺序会影响测试结果。所以我后面采用了分开测多个值的方案。

打印结果如下:

Hashtable:  190  179  178  185  172

Dictionary<object,object>:  184  192  177  184  195

Dictionarty<object,int>:  88  96  87  91  90

Dictionarty<int,int>:  35  35  35  39  36

会发现,当Dictionary的键值的类型越精确,性能越高。

  总结:

  1、Hashtable会把键值转成object存储;(装箱拆箱要消耗性能)

  2、除非键和值的类型都不统一,否则,不要用Hashtable;

  3、Hashtable和Dictionary的关系就像ArrayList和List的关系一样啊。(恍然大悟)

最新文章

  1. 解决NetBeans运行卡顿问题
  2. 北漂的生活 - python 面试
  3. 调整win7 Windows7下时间同步的频率时 钟同步间隔
  4. 微信公众平台开发教程--方培工作室,PHP语言版本
  5. js怎样改变div的宽度
  6. 谈谈asp.net中的&lt;% %&gt;,&lt;%= %&gt;,&lt;%# %&gt;&lt;%$ %&gt;的使用
  7. DirectSound应用
  8. java设计模式之六适配器模式(Adapter)
  9. Redis高可用方案----Redis主从+Sentinel+Haproxy
  10. rsa证书ssh登陆服务器
  11. oracle12C 创建PDB
  12. Python PyCharm编译器
  13. JSP入门实战下
  14. APScheduler API -- apscheduler.triggers.cron
  15. Scala简介及基础语法
  16. centos 7 安装 配置 openvpn 客户端
  17. MTCNN 实现人脸识别
  18. Hibernate(五)
  19. Eolinker——代码注入插入随机参数值
  20. Code Forces Bear and Forgotten Tree 3 639B

热门文章

  1. ionic cordova 安装指定版本
  2. WebLogic登录管理控制台、以及相关问题解决
  3. Android BitmapUtils工具类
  4. OkHttp3源码详解(一) Request类
  5. 工作中常用到的Vim命令
  6. Unable to load DLL &#39;SQLite.Interop.dll&#39;: The specified module could not be found. (Exception from HRESULT: 0x8007007E)
  7. Android (checkBox)
  8. pip安装django的时候提示没有这个命令
  9. VB6 对象库未注册问题
  10. 【PAT】B1084 外观数列(20 分)(纯C)