zoukankan      html  css  js  c++  java
  • C#哈希表(HashTable)和Dictionary比较

    添加数据时Hashtable快。频繁调用数据时Dictionary快。

    Dictionary<K,V>是泛型的,当K或V是值类型时,其速度远远超过Hashtable。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace WindowsFormsApp1
    {
        public class Student
        {
            private string _name;
            private int _age;
    
            public string Name { get => _name; set => _name = value; }
            public int Age { get => _age; set => _age = value; }
            
        }
    }
    private void button1_Click(object sender, EventArgs e)
            {
                Stopwatch sw = new Stopwatch();
    
                Hashtable hashtable = new Hashtable();
    
                Dictionary<int, Student> dict = new Dictionary<int, Student>();
    
                int countNum = 1000000;            
                sw.Start();
                for (int i = 0; i < countNum; i++)
                {
                    Student s = new Student();
                    s.Name = "n" + i.ToString();
                    s.Age = i;
                    hashtable.Add(i, s);
                }
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds);  //输出: 817
    
    
                sw.Restart();
                for (int i = 0; i < countNum; i++)
                {
                    Student s = new Student();
                    s.Name = "n" + i.ToString();
                    s.Age = i;
                    dict.Add(i, s);
                }
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds);  //输出: 859
    
    
    
                sw.Restart();
                for (int i = 0; i < countNum; i++)
                {
                    hashtable.ContainsKey(i);
                    Student s1 =(Student)hashtable[i];
                    string str1 = s1.Name;
                }
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds);  //输出: 137
    
                sw.Restart();
                for (int i = 0; i < countNum; i++)
                {
                    dict.ContainsKey(i);
                    string str=dict[i].Name;
                }
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds);  //输出: 51
    
            }
  • 相关阅读:
    微信用户授权,获取code
    关于swiper在vue中不生效的问题
    ES6-Set 和 Map 数据结构
    Js中caller和callee的区别
    类与对象基础总结--继承,多态
    java 类与对象基础整理
    java 的数据库操作--JDBC
    Socket的长连接和短连接
    java 的底层通信--Socket
    算法--树与递归
  • 原文地址:https://www.cnblogs.com/ike_li/p/7660462.html
Copyright © 2011-2022 走看看