您的位置:首页 > 编程语言 > C#

C# Dictionary字典类介绍

2016-08-31 21:44 295 查看

前言

     最近在做项目的时候,用到了Dictinary<>,觉得很陌生,因为原来只有见过List类是带尖括号的,也不知道为什么要把实体放到Dictionary中,所以就查了一些资料,看了看API文档,发现原来他也是属于泛型类的,下面就来聊一聊这个新朋友吧

概念

      Dictionary 泛型类提供了从一组键到一组值的映射。字典中的每个添加项都由一个值及其相关联的键组成。通过键来检索值的速度是非常快的,接近于 O(1),这是因为 Dictionary 类是作为一个哈希表来实现的。在C#中,Dictionary提供快速的基于键值的元素查找。当你有很多元素的时候可以使用它。他需要引用的命名空间是:System.Collection.Generic

结构

Dictionary<[key],[value]>

自己的理解:可以看出,他的存储结构是通过哈希表来实现的,一个键值,对应一个数据,通过键值就能快速的找出该键值对应的数据。当然键值是不能重复的。

和List<>效率对比

       下边是我写的一个小demo,主要是测试遍历list和dictionary的用时差别

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace dictionaryDemo
{
class Program
{
static void Main(string[] args)
{

Dictionary<int, string> dic = new Dictionary<int, string>();
for (int i = 0; i < 10000000; i++)
{
string a = "v" + i;
dic.Add(i, a);
}

Stopwatch stopwatch1 = new Stopwatch();
stopwatch1.Start(); //  开始监视代码运行时间
foreach (KeyValuePair<int, string> item in dic)
{
if (item.Key==5000000)
{
Console.WriteLine(dic[5000000]);
}

}
stopwatch1.Stop(); //  停止监视

List<string> studentinfo = new List<string>();
//studentModel student=new studentModel();
for (int i = 0; i < 10000000; i++)
{
string b = "b"+i;
studentinfo.Add(b);
}

Stopwatch stopwatch2 = new Stopwatch();
stopwatch2.Start(); //  开始监视代码运行时间
foreach (string item in studentinfo)
{
if (item=="b5000000")
{
Console.WriteLine(studentinfo[5000000]);
}

}
stopwatch2.Stop(); //  停止监视

Console.WriteLine("dictionary查找用时{0}:",stopwatch1.Elapsed );
Console.WriteLine("      list查找用时{0}:",stopwatch2.Elapsed);
Console.ReadLine();

}

}
}


添加用时:



遍历用时:



遍历查找用时:



直接查找用时:



总结

      实验了才知道,其实不是任何时候dictionary都是最快的,我们知道list是以线性表的形式存储的,通过前驱结点和后续节点,找到这个位置,在内存中是连续的区域,而dictionary在内存中是不连续的,所以在查找的时候会产生大量的内存换页操作,而list需要进行最少的内存换页即可,所以直接查找的时候,list效率明显比dictionary要高
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: