C# 并发容器之ConcurrentDictionary与普通Dictionary带锁的性能对比
2016-03-06 21:29
585 查看
结果已经写在注释中
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#学习视频
- C#—运算符、控制流程语句
- C# 笔记(怕电脑抽疯,存起来)
- 抓取网页数据C#文件
- C#成魔之路<6>ADO.NET数据访问技术(2)
- C#综合揭秘——细说多线程
- 解析C#多线程编程中异步多线程的实现及线程池的使用
- C#软件设计——小话设计模式原则之:单一职责原则SRP
- c# checked unchecked 关键字,在需要的时候请记得用他们两位
- 集合
- 【C#】 .net入门之Windows窗体程序
- C#第三节课(2)
- c#中在类名前面加上public有什么用
- C#第三节课(1)
- C# 在指定字符串中间插入换行符
- 对于新手用c#中的delegate(委托)和event(事件)
- c#---写文件
- 转载:C# 之泛型详解
- 用BenchmarkDotNet给C#程序做性能测试
- C#成魔之路<5>ADO.NET数据访问技术(1)