• 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; }
    
        }
  • 相关阅读:
    dubbo支持哪些通信协议?支持哪些序列化协议?
    spring常见面试题
    100道Java基础面试题收集整理(附答案)
    阿里面试题
    说一下的dubbo的工作原理?注册中心挂了可以继续通信吗?说说一次rpc请求的流程?
    为什么要进行系统拆分?如何进行系统拆分?拆分后不用 dubbo 可以吗?
    layui增加转圈效果
    js防止重复提交代码
    工作流表介绍
    权限树的制作(menu)
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/13125901.html
Copyright © 2020-2023  润新知