Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对于c中的小集合,List.Add vs HashSet.Add#_C#_Performance_List_Set - Fatal编程技术网

C# 对于c中的小集合,List.Add vs HashSet.Add#

C# 对于c中的小集合,List.Add vs HashSet.Add#,c#,performance,list,set,C#,Performance,List,Set,给定 或 怀疑的来源:这确实与如何使用数据结构有关。如果需要使用索引访问项目,则不能使用哈希集;如果需要存储重复项,则可以;不要使用HashSet。列表通常用于大多数操作,因此如果您不了解哈希集的基本设计和功能,那么列表就足够了。如果您关心性能(特别是如果您知道您将操作大量项),则应使用哈希集但不要在意订单 要遍历集合时,请使用List。遍历列表中的所有项通常比遍历集合快得多(除非在包含的方法中使用) 检查此样本以测试性能: set.Add (t); const int COUNT=10000

给定


怀疑的来源:

这确实与如何使用数据结构有关。如果需要使用索引访问项目,则不能使用哈希集;如果需要存储重复项,则可以;不要使用HashSet。列表通常用于大多数操作,因此如果您不了解哈希集的基本设计和功能,那么列表就足够了。

如果您关心性能(特别是如果您知道您将操作大量项),则应使用哈希集但不要在意订单

要遍历集合时,请使用List。遍历列表中的所有项通常比遍历集合快得多(除非在包含的方法中使用)

检查此样本以测试性能:

set.Add (t);
const int COUNT=100000;
HashSet hashSetOfInts=新HashSet();
秒表秒表=新秒表();
for(int i=0;i
如果很重要,为什么不试试呢?您对小的定义是什么?根据MSDN列表。如果计数小于内部数组的容量,则Add()和HashSet.Add()都是O(1),如果对象需要调整大小,则都是O(n)。
if (! list.Contains (t)) list.Add (t);
set.Add (t);
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();