首先看下Dictionary的源码

public void Add (TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException ("key"); // get first item of linked list corresponding to given key
int hashCode = hcp.GetHashCode (key) | HASH_FLAG;
int index = (hashCode & int.MaxValue) % table.Length;
int cur = table [index] - 1; // walk linked list until end is reached (throw an exception if a
// existing slot is found having an equivalent key)
while (cur != NO_SLOT) {
// The ordering is important for compatibility with MS and strange
// Object.Equals () implementations
if (linkSlots [cur].HashCode == hashCode && hcp.Equals (keySlots [cur], key))
throw new ArgumentException ("An element with the same key already exists in the dictionary.");
cur = linkSlots [cur].Next;
} if (++count > threshold) {
Resize ();
index = (hashCode & int.MaxValue) % table.Length;
} // find an empty slot
cur = emptySlot;
if (cur == NO_SLOT)
cur = touchedSlots++;
else
emptySlot = linkSlots [cur].Next; // store the hash code of the added item,
// prepend the added item to its linked list,
// update the hash table
linkSlots [cur].HashCode = hashCode;
linkSlots [cur].Next = table [index] - 1;
table [index] = cur + 1; // store item's data
keySlots [cur] = key;
valueSlots [cur] = value; generation++;
}

  

int hashCode = hcp.GetHashCode (key) | HASH_FLAG;

hcp

[Serializable]
sealed class DefaultComparer : EqualityComparer<T> { public override int GetHashCode (T obj)
{
if (obj == null)
return ;
return obj.GetHashCode ();
} public override bool Equals (T x, T y)
{
if (x == null)
return y == null; return x.Equals (y);
}
}

其实就是走到obj.GetHashCode,如果obj.GetHashCode没有覆盖的话,那就会走到ValueType的GetHashCode

public override int GetHashCode ()
{
object[] fields;
int result = InternalGetHashCode (this, out fields); if (fields != null)
for (int i = ; i < fields.Length; ++i)
if (fields [i] != null)
result ^= fields [i].GetHashCode (); return result;
}

注意看

[MethodImplAttribute (MethodImplOptions.InternalCall)]
internal extern static int InternalGetHashCode (object o, out object[] fields);
int result = InternalGetHashCode (this, out fields);
会把this转成object类型,第1次boxing,而且会把每个字段都转成object,放入fields里,所以会有多次gc alloc
这个是不重载GetHashCode导致的gc alloc。
下一个是
if (linkSlots [cur].HashCode == hashCode && hcp.Equals (keySlots [cur], key))

hcp.Equals

如果T没有实现IEquatable,就会走到DefaultCOmparer,然后会走到

这个Equals会调用ValueType.Equals

internal static bool DefaultEquals (object o1, object o2)
{
object[] fields; if (o2 == null)
return false; bool res = InternalEquals (o1, o2, out fields);
if (fields == null)
return res; for (int i = ; i < fields.Length; i += ) {
object meVal = fields [i];
object youVal = fields [i + ];
if (meVal == null) {
if (youVal == null)
continue; return false;
} if (!meVal.Equals (youVal))
return false;
} return true;
} // <summary>
// True if this instance and o represent the same type
// and have the same value.
// </summary>
public override bool Equals (object obj)
{
return DefaultEquals (this, obj);
}

这个里面会把x,y都转成object.所以会有2次boxing

至此所有的boxing都清楚了,工程例子在

https://github.com/yingsz/DictionaryAlloc

消除boxing参考

http://www.bkjia.com/Asp_Netjc/1314145.html

Dictionary里使用struct,enum做key的更多相关文章

  1. C#中正确使用enum做Key的姿势

    C#中自定义enum,然后将其作为Dictionary的Key,通常的做法如下: using System; using System.Text; using System.Collections.G ...

  2. Unity3D研究之多语言用中文做KEY

     做多语言的时候用中文做KEY绝对是有100%的优点,假设用英文表示那么代码里面给文字赋值的地方全都是英文.写的代码多了以后维护起来就没有人能看懂了,或者看起来非常费劲. 对PoolManager ...

  3. React 等框架使用 index 做 key 的问题

    React 等框架使用 index 做 key 的问题 假如有两个树,一个是之前,一个是更变之后,我们抽象成两种可能性. 插入内容在最后 插入内容在最前 关于插在中间,原理一样,就不阐述. 使用 ul ...

  4. Go语言 判断key是否在map里 if _, ok := map[key]; ok

    if val, ok := map[key]; ok { //do something here } 如果key在map里 val 被赋值map[key] ok 是true 否则val得到相应类型的零 ...

  5. c++ struct enum union加typedef与不加typedef

    struct/enum/union加typedef与不加typedef 匿名结构体 struct { int a; int b; } v; // 这里表示定义了一个结构体的变量v,且结构体类型没有名字 ...

  6. 适当使用enum做数据字典 ( .net c# winform csharp asp.net webform )

    在一些应用中,通常会用到很多由一些常量来进行描述的状态数据,比如性别(男.女),审核(未审核.已审核)等.在数据库中一般用数字形式来存储,比如0.1等. 不好的做法 经常看到一些应用(ps:最近又看到 ...

  7. Dictionary通过Value找到它的key

    private void GetDicKeyByValue() { Dictionary<string, string> dic = new Dictionary<string, s ...

  8. Java学习笔记--HashMap中使用object做key的问题【转】

    在HashMap中,如果需要使用多个属性组合作为key,可以将这几个属性组合成一个对象作为key.但是存在的问题是,要做get时,往往没办法保存当初put操作时的key object的referenc ...

  9. C# Dictionary通过value获取对应的key值

    1:最直白的循环遍历方法,可以分为遍历key--value键值对以及所有的key两种表现形式 2:用Linq的方式去查询(当然了这里要添加对应的命名空间 using System.Linq) 如下为一 ...

随机推荐

  1. 李洪强和你一起学习前端之(4)HTML5介绍

    1.1认识HTML5 html的版本: html4 Xhtml1.0 目前: html5是最高的版本 再怎么变化,无非是多了一些标签而已,但是不单单是提供了一些标签 比如: 开发网页游戏 我们可以开发 ...

  2. Xcode 10 关于 CocoaPods 安装失败的问题RuntimeError

    xcode 10的情况下执行pod install报错了 RuntimeError - [!] Xcodeproj doesn't know about the following attribute ...

  3. shell 实现mysql写入操作

    mysql -uroot study -proot << EOF > insert into top_n_movie(movie,sumprice)values('hello kit ...

  4. php-fpm nginx 使用 curl 请求 https 出现 502 错误

    用php curl请求https的url出现502错误,请求帮忙解决. PHP版本:5.6.7Nginx版本:1.8.0 代码如下: $ch = curl_init(); curl_setopt($c ...

  5. IO模型(阻塞、非阻塞、多路复用与异步)

    IO模型 同步IO和异步IO,阻塞IO和非阻塞IO分别是什么,到底有什么区别?不同环境下给出的答案也是不一的.所以先限定一下上下文是非常有必要的. 本文讨论的背景是Linux环境下的network I ...

  6. 6:7 题一起MySQL数据库分库备份

    企业Shell面试题6:MySQL数据库分表备份 请实现对MySQL数据库进行分表备份,用脚本实现. 解答: [root@db01 scripts]# cat fenbiao.sh #!/bin/ba ...

  7. 多线程中wait和notify的理解与使用

    1.对于wait()和notify()的理解 对于wait()和notify()的理解,还是要从jdk官方文档中开始,在Object类方法中有: void notify()  Wakes up a s ...

  8. net mvc 小目标

    1.前台视图去找指定的控制器(非默认) 2.控制器去找指定的视图(非默认)

  9. 使用html替代excel导出数据的优势和技巧

    之前一直使用NPOI或者微软office官方组件导出excel,但是多多少少会有写小问题,不是数据量不能过大(xls的问题,用xlsx就可以更大了),就是速度慢,或者文件体积太大 中途采用过csv(逗 ...

  10. 【BZOJ】2018: [Usaco2009 Nov]农场技艺大赛(暴力)

    http://www.lydsy.com/JudgeOnline/problem.php?id=2018 精度问题我也是醉了.. #include <cstdio> #include &l ...