標籤:oid ons edm tostring get contains windows console 添加
添加資料時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 }
C#雜湊表(HashTable)和Dictionary比較