結論:
總數 50000 (5萬): List 檢索 5W次 耗時 23秒, HashSet 檢索 5W次 耗時 0.01秒。
總數 5000 (5千): List 檢索 5K次 耗時 0.16秒, HashSet 檢索 5K次 耗時 0.001秒。
總數 500 (5百): List 檢索 500次 耗時 0.004秒, HashSet 檢索 500次 耗時 0.000秒。
總數 50 : List 檢索 50次 耗時 0.002秒, HashSet 檢索 500次 耗時 0.000秒。
集合查找元素,
當總數超過 10 時, HashSet<T> 的檢索性能 就會比 List<T> 快。
當總數超過 1000 時, List<T> 的檢索性能 會 急速下降。
當總數超過 10000 時, List<T> 將會以 秒 為單位 的損失性能。
換言之:
> 無論怎樣的數據量, HashSet<T> 的檢索速度 都要比 List<T> 快。(不存在那種: 多少數據量以下,List 有優勢,多少數據量以上,HashSet 有優勢)
> Hastable 的查找性能 == HashSet 的查找性能,用不了 HashSet 可以用 Hashtable 替換。
背景:
今天在項目中,需要用到一個 檢索功能,只需要判斷 指定的關鍵字 是否存在。
第一本能就想到了 HashSet<T> 對象。
但,HashSet<T> 是 .Net 4.0 的東西,我希望自己的代碼 無限兼容 .Net 2.0 —— 所以想避開這個東西。
其實,我的關鍵字 最多不過 20個,但是檢索次數比較多 —— 所以,我就想看一下 List 和 HashSet 查找的 分水嶺 在哪里。
測試代碼:
1 static void Main(string[] args) 2 { 3 List<string> list = new List<string>(); 4 HashSet<string> hash = new HashSet<string>(); 5 6 //數據准備 7 for (int i = 0; i < 5000; i++) 8 { 9 string str = Guid.NewGuid().ToString(); 10 list.Add(str); 11 hash.Add(str); 12 } 13 Console.WriteLine("數據准備完成"); 14 15 16 //list 的查找性能 17 DateTime time0 = DateTime.Now; 18 bool result0 = true; 19 foreach (string str in list) 20 { 21 bool v = list.Contains(str); //list 的查找性能 22 result0 = result0 && v; 23 } 24 DateTime time1 = DateTime.Now; 25 Console.WriteLine("從 {0} 的 List<string> 中, 判斷數據是否存在, 耗時: {1}", list.Count, (time1 - time0).TotalSeconds); 26 27 28 29 //hash 的查找性能 30 DateTime time2 = DateTime.Now; 31 bool result1 = true; 32 foreach (string str in list) 33 { 34 bool v = hash.Contains(str); //hash 的查找性能 35 result1 = result1 && v; 36 } 37 DateTime time3 = DateTime.Now; 38 Console.WriteLine("從 {0} 的 HashSet<string> 中, 判斷數據是否存在, 耗時: {1}", hash.Count, (time3 - time2).TotalSeconds); 39 40 41 Console.ReadKey(); 42 }
運行截圖:
Hashtable 性能:
.Net 2.0 沒有 HashSet,但是有 Hashtable 和 Dictionary
Hashtable 支持 Key查找 和 Value查找
1 //hashtable - key 的查找性能 2 DateTime time4 = DateTime.Now; 3 bool result2 = true; 4 foreach (string str in list) 5 { 6 bool v = hash2.ContainsKey(str); //hashtable - key 的查找性能 7 result2 = result2 && v; 8 } 9 DateTime time5 = DateTime.Now; 10 Console.WriteLine("從 {0} 的 Hashtable 中, 判斷Key是否存在, 耗時: {1}", hash2.Count, (time5 - time4).TotalSeconds); 11 12 13 //hashtable - value 的查找性能 14 DateTime time6 = DateTime.Now; 15 bool result3 = true; 16 foreach (string str in list) 17 { 18 bool v = hash2.ContainsValue(str); //hashtable - value 的查找性能 19 result3 = result3 && v; 20 } 21 DateTime time7 = DateTime.Now; 22 Console.WriteLine("從 {0} 的 Hashtable 中, 判斷Value是否存在, 耗時: {1}", hash2.Count, (time7 - time6).TotalSeconds);
測試結果如下: