2014-09-02 16 views

回答

2

這真的與你將如何使用這些數據結構做。如果您需要使用索引訪問項目,那麼您不能使用HashSet,而且如果您需要存儲重複項目,則可以使用HashSet。 List通常用於大多數操作,所以我不明白HashSet的底層設計和功能,那麼List就足夠了。 enter image description here

+0

根據MSDN List.Add()和HashSet.Add()如果count小於內部數組的容量,則O(1)和O(n)如果對象需要調整大小。 – Almis 2018-01-16 12:34:35

1

HashSet應該在您關心性能的情況下使用(特別是如果您知道您將在大量項目上操作)但不關心訂單。

使用列表當你想遍歷集合。迭代列表中的所有項目通常比通過集合更快(除非在內部使用諸如Contains之類的方法)。

檢查該樣品的測試性能:

const int COUNT = 100000; 
     HashSet<int> hashSetOfInts = new HashSet<int>(); 
     Stopwatch stopWatch = new Stopwatch(); 
     for (int i = 0; i < COUNT; i++) 
     { 
      hashSetOfInts.Add(i); 
     } 

     stopWatch.Start(); 
     for (int i = 0; i < COUNT; i++) 
     { 
      hashSetOfInts.Contains(i); 
     } 
     stopWatch.Stop(); 

     Console.WriteLine(stopWatch.Elapsed); 

     stopWatch.Reset(); 
     List<int> listOfInts = new List<int>(); 
     for (int i = 0; i < COUNT; i++) 
     { 
      listOfInts.Add(i); 
     } 

     stopWatch.Start(); 
     for (int i = 0; i < COUNT; i++) 
     { 
      listOfInts.Contains(i); 
     } 
     stopWatch.Stop(); 

     Console.WriteLine(stopWatch.Elapsed); 
     Console.Read();