C# 解决在Dictionary中使用枚举的效率问题

使用字典的好处

System.Collections.Generic命名空间下的Dictionary,它的功能非常好用,且功能与现实中的字典是一样的。

它同样拥有目录和正文,目录用来进行第一次的粗略查找,正文进行第二次精确查找。通过将数据进行分组,形成目录,正文则是分组后的结果。它是一种空间换时间的方式,牺牲大的内存换取高效的查询效率。所以,功能使用率查询>新增时优先考虑字典。

        public static Tvalue DicTool<Tkey, Tvalue>(Tkey key, Dictionary<Tkey, Tvalue> dic)
        {
            return dic.TryGetValue(key, out Tvalue _value) ? _value : (Tvalue)default;
        }
           Stopwatch stopwatch = Stopwatch.StartNew();
            for (int i = 0; i < 1; i++)
            {
                DicTool(0, Dic);
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);

执行时间00:00:00.0003135

            Stopwatch stopwatch = Stopwatch.StartNew();
            for (int i = 0; i < 10000; i++)
            {
                DicTool(0, Dic);
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);

执行时间00:00:00.0005091

从上面可以看出,它进行大量查询时的用时非常短,查询效率极高。但使用时需要避免使用枚举作为关键词进行查询;它会造成查询效率降低。

使用枚举作为key时查询效率变低

 Stopwatch stopwatch = Stopwatch.StartNew();
            for (int i = 0; i < 10000; i++)
            {
                DicTool(MyEnum.one, Dic);
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);

执行时间00:00:00.0011010

从这里的执行时间可以看出,查询效率大大降低。

优化方案: 使用int代替enum,enum强制转型后间接查询;可使查询效率与非枚举的直接查询相近。(还有其他的优化方案,个人只使用过这个)

using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace Test
{
    public class Program
    {
        public enum MyEnum : int
        {
            one,
            two,
            three
        }
        public static void Main(string[] args)
        {
            Dictionary<int, int> Dic = new Dictionary<int, int>()
            {
                { (int)MyEnum.one,1},
                { (int)MyEnum.two,2},
                { (int)MyEnum.three,3}
            };
            Stopwatch stopwatch = Stopwatch.StartNew();
            for (int i = 0; i < 10000; i++)
            {
                DicTool((int)MyEnum.one, Dic);
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);
        }
        public static Tvalue DicTool<Tkey, Tvalue>(Tkey key, Dictionary<Tkey, Tvalue> dic)
        {
            return dic.TryGetValue(key, out Tvalue _value) ? _value : (Tvalue)default;
        }
    }
}

执行时间 00:00:00.0005005

为什么使用枚举会降低效率

使用ILSpy软件反编译源码,得到以下:

public bool TryGetValue(TKey key, out TValue value)
{
    int num = this.FindEntry(key);
    if (num >= 0)
    {
        value = this.entries[num].value;
        return true;
    }
    value = default(TValue);
    return false;
}
private int FindEntry(TKey key)
{
    if (key == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    }
    if (this.buckets != null)
    {
        int num = this.comparer.GetHashCode(key) & 2147483647;
        for (int i = this.buckets[num % this.buckets.Length]; i >= 0; i = this.entries[i].next)
        {
            if (this.entries[i].hashCode == num && this.comparer.Equals(this.entries[i].key, key))
            {
                return i;
            }
        }
    }
    return -1;
}

查看Dictionary源码后可以知道,效率减低来源于this.comparer.GetHashCode(key) 这段代码。

comparer是使用了泛型的成员,它内部使用int类型不会发生装箱,但是由于Enum没有IEquatable接口,内部运行时会引起装箱行为,该行为降低了查询的效率。

IEquatable源码:

namespace System
{
 [__DynamicallyInvokable]
 public interface IEquatable<T>
 {
  [__DynamicallyInvokable]
  bool Equals(T other);
 }
}

装箱:值类型转换为引用类型(隐式转换)

把数据从栈复制到托管堆中,栈中改为存储数据地址。

拆箱:引用类型转换为值类型(显式转换)

补充:C#中Dictionary<Key,Value>中[]操作的效率问题

今天有朋友问到如果一个Dictionary<Key,Value>中如果数据量很大时,那么[ ]操作会不会效率很低。

感谢微软开源C#,让我们有机会通过代码验证自己的猜想。

此处是微软C#的源代码地址

先上结论:Dictionary<Key,Value>的[ ]操作的时间 = 一次调用GetHashCode + n次调用Key.Equals的时间之和。

期中n受传入的key的GetHashCode 的重复率影响,比如传入的key的hash值为5,Dictionary中hash值为5的值有100个,这100值相当于用链表存储,如果要查找的值在第20个那么n的值就是19。如果GetHashCode 基本没什么重复率,那么n始终1,极端情况下n可能为一个很大的数(参考测试代码)。

C#中的关键代码如下:

 int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
                for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
                    if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;

同时在这里我想说一下Dictionary<Key,Value>类中数据的组织结构:

        private struct Entry {
            public int hashCode;    // Lower 31 bits of hash code, -1 if unused
            public int next;        // Index of next entry, -1 if last
            public TKey key;           // Key of entry
            public TValue value;         // Value of entry
        }
        private int[] buckets;
        private Entry[] entries;

期中buckets是保存所有的相同hash值的Entry的链表头,而相同hash值的Entry是通过Entry .next连接起来的。在新加入的Value时,如果已经存在相同hash值会将buckets中的值更新,如果不存在则会加入新的值,关键代码如下:

            entries[index].hashCode = hashCode;
            entries[index].next = buckets[targetBucket];
            entries[index].key = key;
            entries[index].value = value;
            buckets[targetBucket] = index;

注意最后一句,将新加入值的下标inddex的值赋值给了buckets,这样相当于就更新了链表头指针。这个链表就是前面产生n的原因。

下面我放一些测试的结果:

当GetHashCode的消耗为1ms时:

当GetHashCode的消耗为100ms时:

增加的消耗是99ms也就是GetHashCode增加的消耗,后面的尾数就是上面公式里的n。

附测试代码如下:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication1
{
    class Program
    {
        public class Test1
        {
            private ushort num = 0;
            public Test1(ushort a)
            {
                num = a;
            }

            public override int GetHashCode()
            {
                Thread.Sleep(1);
                return num / 100;
            }

            public override bool Equals(object obj)
            {
                Thread.Sleep(1);
                return num.Equals((obj as Test1).num);
            }
        }

        static void Main(string[] args)
        {
            Dictionary<Test1, string> testDic = new Dictionary<Test1, string>();
            for (ushort a = 0; a < 100; a++)
            {
                Test1 temp = new Test1(a);
                testDic.Add(temp, a.ToString());
            }

            Stopwatch stopWatch = new Stopwatch();
            string str = "";

            stopWatch.Start();
            str = testDic[new Test1(99)];
            stopWatch.Stop();
            Console.WriteLine("num = " + str +" pass Time = " + stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();
            str = testDic[new Test1(1)];
            stopWatch.Stop();
            Console.WriteLine("num = " + str + " pass Time = " + stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();
            str = testDic[new Test1(50)];
            stopWatch.Stop();
            Console.WriteLine("num = " + str + " pass Time = " + stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();
            str = testDic[new Test1(98)];
            stopWatch.Stop();
            Console.WriteLine("num = " + str + " pass Time = " + stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();
            str = testDic[new Test1(97)];
            stopWatch.Stop();
            Console.WriteLine("num = " + str + " pass Time = " + stopWatch.ElapsedMilliseconds);
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

(0)

相关推荐

  • C#字典Dictionary的用法说明(注重性能版)

    前言 以键值对Dictionary<[key], [value]>形式存值,和哈希表很像也是一种无序的结构. 要使用Dictionary,需要先导入C#泛型命名空间System.Collections.Generic Dictionary需要注意的特性 1.任何键都必须是唯一的 --> 不能添加相同key的键值对,不然就报错: 如果要修改已有key对应的value,可以这样做: 2.Unity5.4以下的版本,最好不要用foreach来遍历字典: 法一:foreach遍历字典,会生成GC

  • c# 用Dictionary实现日志数据批量插入

    背景 最近再做一个需求,就是对站点的一些事件进行埋点,说白了就是记录用户的访问行为.那么这些数据怎么保存呢,人家点一下保存一下?显然不合适,肯定是需要批量保存,提高效率. 问题窥探 首先,我想到的是Dictionary,对于C#中的Dictionary类相信大家都不陌生,这是一个Collection(集合)类型,可以通过Key/Value(键值对的形式来存放数据:该类最大的优点就是它查找元素的时间复杂度接近O(1),实际项目中常被用来做一些数据的本地缓存,提升整体效率.Dictionary是非线

  • C#中数组、ArrayList、List、Dictionary的用法与区别浅析(存取数据)

    前言 在工作中经常遇到C#数组.ArrayList.List.Dictionary存取数据,但是该选择哪种类型进行存储数据,对于初学者的我一直不知道该怎么取舍.于是抽空好好看了下他们的用法和比较,在这里总结下来,后面有需要改进的再更新. 初始化 数组: int[] buff = new int[6]; ArrayList: ArrayList buff = new ArrayList(); List: List<int> buff = new List<int>(); Dictio

  • C#常见的几种集合 ArrayList,Hashtable,List<T>,Dictionary<K,V> 遍历方法对比

    一.先来分别介绍一下ArrayList,Hashtable,List<T>,Dictionary<K,V> 1.ArrayList动态数组,保存值的时候比较好用 2.Hashtable以存储键值对的方式存储.value,和key 3.List<T> 和 Dictionary<K,V> 应该是泛型吧,可以保存实体类 二.各种集合的遍历方法演示 1.ArrayList ArrayList list = new ArrayList(); //for遍历 for (

  • c# List和Dictionary常用的操作

    本文主要汇总了在开发过程中,使用List和Dictionary常用的方法,例如增.删.改.查.排序等等各种常用操作. 在平时的开发过程中,List和Dictionary是我们经常使用到的数据结构,而且由于本人记性又差有些方法长时间不用就都忘了,所以总结出此博客,用于记录和分享一下关于这两种数据结构的使用方法. 一.List 首先对于这些内容最权威和完整介绍的地方就是微软的官方文档,里面全面且详细的介绍了Lits的所有属性及方法,经常查看官方文档是一个非常好的习惯.本文将会总结出在日常开发过程中相

  • C#并发容器之ConcurrentDictionary与普通Dictionary带锁性能详解

    结果已经写在注释中 static void Main(string[] args) { var concurrentDictionary = new ConcurrentDictionary<int, string>(); var dictionary = new Dictionary<int, string>(); var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { lock (

  • C#中Dictionary<TKey,TValue>排序方式的实现

    自定义类: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp中Dictionary排序方式 { [Serializable] public class CustmonizedClass { public string stuName { get; set; } public int

  • 聊聊C# 中HashTable与Dictionary的区别说明

    1. 哈希表(HashTable)简述 在.NET Framework中,Hashtable是System.Collections命名空间提供的一个容器,用于处理和表现类似keyvalue的键值对,其中key通常可用来快速查找,同时key是区分大小写:value用于存储对应于key的值.Hashtable中keyvalue键值对均为object类型,所以Hashtable可以支持任何类型的keyvalue键值对. 2. 什么情况下使用哈希表 (1)某些数据会被高频率查询(2)数据量大(3)查询字

  • C#数组中List, Dictionary的相互转换问题

    本篇文章会向大家实例讲述以下内容: 将数组转换为List 将List转换为数组 将数组转换为Dictionary 将Dictionary 转换为数组 将List转换为Dictionary 将Dictionary转换为List 首先这里定义了一个"Student"的类,它有三个自动实现属性. class Student { public int Id { get; set; } public string Name { get; set; } public string Gender {

  • C# ArrayList、HashSet、HashTable、List、Dictionary的区别详解

    在C#中,数组由于是固定长度的,所以常常不能满足我们开发的需求. 由于这种限制不方便,所以出现了ArrayList. ArrayList.List<T> ArrayList是可变长数组,你可以将任意多的数据Add到ArrayList里面.其内部维护的数组,当长度不足时,会自动扩容为原来的两倍. 但是ArrayList也有一个缺点,就是存入ArrayList里面的数据都是Object类型的,所以如果将值类型存入和取出的时候会发生装箱.拆箱操作(就是值类型与引用类型之间的转换),这个会影响程序性能

随机推荐