C# HashSet UnionWith()方法';C语言中的s性能问题#

C# HashSet UnionWith()方法';C语言中的s性能问题#,c#,performance,list,hashset,C#,Performance,List,Hashset,我有许多包含不同索引异常的HashSet。我根据输入数据将这些HashSet组合成一个大的HashSet。出于测试目的,我还将HashSet移植到了List类似物中 HashSet和List的唯一目的是从随机数生成中排除索引 这就是我在List的案例中所做的: list2 = new List<int>(); for (int d = 0; d < list1.Count; d++) { if (dicCat4[30].ContainsKey(list1[d]))

我有许多包含不同索引异常的
HashSet
。我根据输入数据将这些HashSet组合成一个大的
HashSet
。出于测试目的,我还将
HashSet
移植到了
List
类似物中

  • HashSet
    List
    的唯一目的是从随机数生成中排除索引
这就是我在List的案例中所做的:

list2 = new List<int>();
for (int d = 0; d < list1.Count; d++)
{
  if (dicCat4[30].ContainsKey(list1[d]))
  {
    list2.AddRange(dicCat4[30][list1[d]]);
  }
}

rand = 2 * RandString.Next(0 / 2, (dicCat[30].Count) / 2);
while (list2.Contains(rand))
{
  rand = 2 * RandString.Next(0 / 2, (dicCat[30].Count) / 2);
}
// action with random
在这种情况下,我使用
UnionWith()
方法来合并索引异常的
HashSet
,而不是
AddRange()

奇怪的是,经过数千次迭代,
List
方法的整体性能更好,但根据许多资料来源,
哈希集
应该执行得更快。Performance profiler显示,HashSet的
UnionWith()
方法是最大的性能瓶颈

我只是好奇-有没有办法让
HashSet
解决方案执行得更快?
(我突然想到了一个好主意:我可以在每个单独的HashSet上使用
Contains(rand)
,因此跳过
UnionWith()
方法)

请注意,哈希集和列表可从以下位置检索:

static Dictionary<int, Dictionary<int, HashSet<int>>> dicCat3;
static Dictionary<int, Dictionary<int, List<int>>> dicCat4;
静态字典dicCat3;
静态字典dicCat4;
编辑:核心迭代解决方案

int inter = list1.Count;
int cco = 0;

while (inter != cco)
{
  cco = 0;

  rand = 2 * RandString.Next(0 / 2, (dicCat[30].Count) / 2);

  for (int d = 0; d < list1.Count; d++)
  {
    if (dicCat4[30].ContainsKey(list1[d]))
    {
      if (!dicCat3[30]][list1[d]].Contains(rand))
      {
        cco++;
      }
      else
      {
        break;
      }
   }
   else
   {
     cco++;
   }
 }
}
int inter=list1.Count;
int-cco=0;
while(inter!=cco)
{
cco=0;
rand=2*RandString.Next(0/2,(dicCat[30].Count)/2);
for(int d=0;d
如果您想在编辑中获得一点性能,请交换您的If/else。C#假设else子句更可能,因此首先计算该树!你应该在那里剃掉几个M。但除此之外,我找不到一个真正的方法来拯救你


如果你发布了一个我可以导入的解决方案,那么我会很高兴地玩一玩,看看我能做些什么,但我不会为了好玩而把它全部打印出来!;)

尝试使用SortedSet而不是HashSet。

2仅用于生成偶数。0表示最小范围为0(零)。最大值为(dicCat[30]。计数)。i、 e.rand=[from 0 to(dicCat[30].Count)]那么,List.AddRange不会检查唯一性,而HashSet.UnionWith会检查唯一性……是的,List有一些重复。我的意思是,由于AddRange只是将新值附加到列表中,因此它会比UnionWith更快,同时检查添加的值不会创建重复项(即使速度不是那么快)。无论如何,HashSet的循环调用Contains应该更快(如果多次调用,速度会更快)。@digEmAll你能检查我的HashSet循环解决方案吗(请参见编辑)。。我在编写代码时几乎失去了理智。。所以可能会有一些错误,但实际上它的执行速度比列表快一点!Hm交换if和else分支就是这样一个微观优化。这是物理处理器级别上的优化。但如果她想从中挤出每一点速度,那就是一种改进!:PIs这是因为分支预测?
int inter = list1.Count;
int cco = 0;

while (inter != cco)
{
  cco = 0;

  rand = 2 * RandString.Next(0 / 2, (dicCat[30].Count) / 2);

  for (int d = 0; d < list1.Count; d++)
  {
    if (dicCat4[30].ContainsKey(list1[d]))
    {
      if (!dicCat3[30]][list1[d]].Contains(rand))
      {
        cco++;
      }
      else
      {
        break;
      }
   }
   else
   {
     cco++;
   }
 }
}