List.Add vs HashSet.Add for c#中的小集合

特定

HashSet set; List list; T t; 

哪些对SMALL集合表现更好?

 if (! list.Contains (t)) list.Add (t); 

要么

 set.Add (t); 

怀疑来源: HashSet vs. List性能

这实际上与您将如何使用数据结构有关。 如果需要使用索引访问项目,则不能使用HashSet,如果需要存储重复项,则可以使用HashSet。 List通常用于大多数操作,因此我不了解HashSet的底层设计和function,那么List就足够了。 在此处输入图像描述

如果您关心性能(特别是如果您知道将对大量项目进行操作)但不关心订单,则应使用HashSet

如果要迭代集合,请使用List 。 迭代List中的所有项目通常比通过集合更快(除非你在像Contains这样的方法中使用)。

检查此示例以测试性能:

 const int COUNT = 100000; HashSet hashSetOfInts = new HashSet(); 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 listOfInts = new List(); 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();