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 (dictionary)
        {
            dictionary[i] = Item;
        }
    }
    sw.Stop();
    Console.WriteLine("wrinting to dictionary with a lock: {0}", sw.Elapsed);
    //wrinting to dictionary with a lock: 00:00:00.0633939
    sw.Restart();
    for (int i = 0; i < 1000000; i++)
    {
        concurrentDictionary[i] = Item;
    }
    sw.Stop();
    Console.WriteLine("wrinting to a concurrent dictionary: {0}", sw.Elapsed);
    //wrinting to a concurrent dictionary: 00:00:00.2889851
    //对于写入操作并发词典要比普通带锁词典要慢
    sw.Restart();
    for (int i = 0; i < 1000000; i++)
    {
        lock (dictionary)
        {
            CurrentItem = dictionary[i];
        }
    }
    sw.Stop();
    Console.WriteLine("reading from dictionary with a lock: {0}", sw.Elapsed);
    //reading from dictionary with a lock: 00:00:00.0286066
    sw.Restart();
    for (int i = 0; i < 1000000; i++)
    {
        CurrentItem = concurrentDictionary[i];
    }
    sw.Stop();
    Console.WriteLine("reading from a concurrent dictionary: {0}", sw.Elapsed);
    //reading from a concurrent dictionary: 00:00:00.0196372
    //对于读取操作并发词典要比普通带锁词典要快
    //concurrentDictionary采用细粒度锁定[fine-grained locking]
    //普通带锁dictionary采用粗粒度锁定[coarse-grained locking]
    //在多核多线程的情况下concurrentDictionary将有更好的性能表现
    sw.Restart();
    Console.ReadKey();
}
const string Item = "Dictionary item";
public static string CurrentItem;

补充:C#中普通字典(Dictionary)、并发字典(ConcurrentDictionary)、和哈希表(Hashtable)读写性能比较

一、说明

程序有时候需要并发多线程操作,多线程读取同一个容器内的东西是可以的,但是如果需要修改及写入到同一容器内,会有索引失败的问题,即两个进程同时向同一个位置写入内容,这种情况下需要通过lock(var),将容器锁定,也可以直接使用可并发读写的容器(ConcurrentDictionary)

测试分2部分,一次是写入操作,包含带锁写入和不带锁写入,其中每个里面又细分为写入字符串和写入一个类,还有一次是遍历操作,同样包含带锁读和不带锁读,其中也分为读取字符串和读取类。

二、测试结果

2.1、写入用时

2.2、遍历用时

2.3、结论

对于写入操作速度:普通词典 > HashTable > 并发词典

对于读操作速度:并发字典 > 带锁字典 > HashTable

无论普通字典还是HashTable,带锁花费的时间都要比不带锁慢,为了线程安全,肯定要牺牲时间的。

所以如果需要自己写入的话,推荐带锁普通字典,读写速度都很均衡。

三、测试代码如下

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BaseMultiThread
{
    class Program
    {
        static void Main(string[] args)
        {
            ConcurrentDictionary<int, string> _CctDic= new ConcurrentDictionary<int, string>();
            ConcurrentDictionary<int, Student> _CctDicClass = new ConcurrentDictionary<int, Student>();
            Dictionary<int, string> _Dic = new Dictionary<int, string>();
            Dictionary<int, Student> _DicClass = new Dictionary<int, Student>();
            Hashtable _Ht = new Hashtable();
            Hashtable _HtClass = new Hashtable();
            string _CurrentItem = "";
            const string _Item = "字符串";
            const int _NUM = 10000000;//执行次数
            Student _CurrentStudent = null;
            Student student = new Student { Name = _Item, Age = 23 };
            Stopwatch _SW = new Stopwatch();

            //字符串写入字典(无锁)
            _SW.Start();

            for (int i = 0; i < _NUM; i++)
            {
                _Dic[i] = _Item;
            }
            _SW.Stop();
            Console.WriteLine("向字典写入【字符串】不添加锁(Lock)花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //字符串写入字典(有锁)
            _Dic = new Dictionary<int, string>();
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                lock (_Dic)
                {
                    _Dic[i] = _Item;
                }
            }
            _SW.Stop();
            Console.WriteLine("向字典写入【字符串】添加锁(Lock)花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //类写入字典(无锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _DicClass[i] = student;
            }
            _SW.Stop();
            Console.WriteLine("向子典写入【学生类】不添加锁(Lock)花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //类写入字典(有锁)
            _DicClass = new Dictionary<int, Student>();
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                lock (_DicClass)
                {
                    _DicClass[i] = student;
                }
            }
            _SW.Stop();
            Console.WriteLine("向子典写入【学生类】添加锁(Lock)花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);
            Console.WriteLine("----------------------------------------------------");

            //字符串写入HashTable(无锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _Ht[i] = _Item;
            }
            _SW.Stop();
            Console.WriteLine("向HashTable写入【字符串】不添加锁(Lock)花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //字符串写入HashTable(有锁)
            _Ht = new Hashtable();
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                lock (_Ht)
                {
                    _Ht[i] = _Item;
                }
            }
            _SW.Stop();
            Console.WriteLine("向HashTable写入【字符串】添加锁(Lock)花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //类写入HashTable(无锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _HtClass[i] = student;
            }
            _SW.Stop();
            Console.WriteLine("向HashTable写入【学生类】不添加锁(Lock)花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //类写入HashTable(有锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                lock (_HtClass)
                {
                    _HtClass[i] = student;
                }
            }
            _SW.Stop();
            Console.WriteLine("向HashTable写入【学生类】添加锁(Lock)花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);
            Console.WriteLine("----------------------------------------------------------");

            //字符串写入ConcurrentDictionary
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _CctDic[i] = _Item;
            }
            _SW.Stop();
            Console.WriteLine("向ConcurrentDictionary写入【字符串】 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //类写入ConcurrentDictionary
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _CctDicClass[i] = student;
            }
            _SW.Stop();
            Console.WriteLine("向ConcurrentDictionary写入【学生类】 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);
            Console.WriteLine("--------------------------------------------------------");

            //遍历普通字典(无锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _CurrentItem = _Dic[i];
            }
            _SW.Stop();
            Console.WriteLine("遍历【普通】字典(无锁) 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //遍历普通字典(有锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                lock (_Dic)
                {
                    _CurrentItem = _Dic[i];
                }
            }
            _SW.Stop();
            Console.WriteLine("遍历【普通】字典(有锁) 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //遍历类字典(无锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _CurrentStudent = _DicClass[i];
            }
            _SW.Stop();
            Console.WriteLine("遍历【学生类】字典(无锁) 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //遍历类字典(有锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                lock (_Dic)
                {
                    _CurrentStudent = _DicClass[i];
                }
            }
            _SW.Stop();
            Console.WriteLine("遍历【学生类】字典(有锁) 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);
            Console.WriteLine("--------------------------------------------------------");

            //遍历HashTable(无锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _CurrentItem = _Ht[i].ToString();
            }
            _SW.Stop();
            Console.WriteLine("遍历【HashTable】字典(无锁) 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //遍历HashTable(有锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                lock (_Dic)
                {
                    _CurrentItem = _Ht[i].ToString();
                }
            }
            _SW.Stop();
            Console.WriteLine("遍历【HashTable】字典(有锁) 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //遍历HashTable类(无锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _CurrentStudent = (Student)_HtClass[i];
            }
            _SW.Stop();
            Console.WriteLine("遍历【HashTable学生类】字典(无锁) 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //遍历HashTable类(有锁)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                lock (_Dic)
                {
                    _CurrentStudent = (Student)_HtClass[i];
                }
            }
            _SW.Stop();
            Console.WriteLine("遍历【HashTable学生类】字典(有锁) 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);
            Console.WriteLine("--------------------------------------------------------");

            //遍历ConCurrent字典
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _CurrentItem = _CctDic[i];
            }
            _SW.Stop();
            Console.WriteLine("遍历【ConCurrent字典】(字符串) 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);

            //遍历ConCurrent字典(类)
            _SW.Restart();
            for (int i = 0; i < _NUM; i++)
            {
                _CurrentStudent = _CctDicClass[i];
            }
            _SW.Stop();
            Console.WriteLine("遍历【ConCurrent字典】(学生类) 花费时间为:{0} 毫秒", _SW.Elapsed.TotalMilliseconds);
	    Console.WriteLine("--------------------------------------------------------");
            _SW.Restart();
            Console.WriteLine("-------------------结束---------------------------");
            Console.ReadLine();
        }
    }//Class_end
    public class Student
    {
        public string Name;
        public int Age;
    }
}

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

(0)

相关推荐

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

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

  • c# List和Dictionary常用的操作

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

  • 聊聊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# 解决在Dictionary中使用枚举的效率问题

    使用字典的好处 System.Collections.Generic命名空间下的Dictionary,它的功能非常好用,且功能与现实中的字典是一样的. 它同样拥有目录和正文,目录用来进行第一次的粗略查找,正文进行第二次精确查找.通过将数据进行分组,形成目录,正文则是分组后的结果.它是一种空间换时间的方式,牺牲大的内存换取高效的查询效率.所以,功能使用率查询>新增时优先考虑字典. public static Tvalue DicTool<Tkey, Tvalue>(Tkey key, Di

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

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

  • 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# 用Dictionary实现日志数据批量插入

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

  • 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#中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#常见的几种集合 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 (

随机推荐