Hashtable、Dictionary、HashSet、List的区别

Hashtable、Dictionary:使用方式类似,都是存储键值对

Hashtable:

Hashtable存储键值对,key、value都是object类型

Hashtable是线程安全的,线程安全实现方式:Hashtable类中有个类SyncHashtable ,封装Hashtable实例,SyncHashtable就是一个装饰器,内部使用lock保证线程安全

private static Hashtable ht1 = Hashtable.Synchronized ( new Hashtable () );//Hashtable.Synchronized()返回Hashtable的同步包装(线程安全)

 Dictionary:

是泛型,不需要装拆箱

Dictionary不是线程安全的,如果多线程环境可以使用ConcurrentDictionary 

HashTable和Dictionary的区别:

HashTable和Dictionary使用方式差不多,但是他们的实现方式时不同的,Dictionary俗称字典,里面存放的时键值对,即KeyValuePair,且支持泛型,而HashTable国内译为散列表,HashTable里面存的key时以散列的方式存储的,但是Dictionary里面是按顺序的方式存的KeyValuePair。

因为上面这个特性,如果大数据量查找时,HashTable会比Dictionary快,因为HashTable查找不需要遍历。

HashSet、List:使用方式类似,都是存储一组成员

List<>:

泛型,可变长度,内存连续分配,只要内存是连续分配的都可以使用索引访问。

Hashset<>:

反省,查询效率高,所以如果元素较多,有查询需求,使用此类型。

List与HashSet查询性能比较:

static void Main(string[] args)
        {
            List<Geography> geoList = new List<Geography>();
            HashSet<Geography> geoSet = new HashSet<Geography>();
            //添加30W测试数据
            for (int i = 0; i < 500000; i++)
            {
                geoSet.Add(new Geography { ID=i,Name="beijing",Type=2});
                geoList.Add(new Geography { ID = i, Name = "beijing", Type = 2 });
            }
            geoSet.Add(new Geography { ID = 100001, Name = "USA", Type = 1 });
            geoList.Add(new Geography { ID = 100001, Name = "USA", Type = 1 });

            Stopwatch sw = new Stopwatch();
            sw.Start();
            var item =geoList.FirstOrDefault(g => g.Name == "USA" && g.Type==1);
            sw.Stop();
           
            Console.WriteLine($"list耗时{ sw.ElapsedMilliseconds}");//list耗时13ms

            sw.Reset();
            item = geoSet.First(g => g.Name == "USA" && g.Type == 1);
            sw.Stop();
            Console.WriteLine($"set耗时{sw.ElapsedMilliseconds}");//set耗时0ms


            Console.ReadKey();
        }
    }
    public class Geography
    {
        public long ID { get; set; }
        public string Name { get; set; }
        public int Type { get; set; }

    }
原文地址:https://www.cnblogs.com/fanfan-90/p/13125901.html