c# - HashSet UnionWith()方法在C#中的性能问题

标签 c# performance list hashset

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

  • HashSetList 的唯一目的是从随机数生成中排除索引。

这就是我在 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

如您所见,所有异常(索引)都使用 AddRange() 合并到一个列表中。使用 Contains() 方法,我们检查随机数是否在列表中。

同样的操作可以用HashSet来完成:

excludehash = new HashSet<int>();

for (int d = 0; d < list1.Count; d++)
{
  if (dicCat4[30].ContainsKey(list1[d]))
  {
    excludehash.UnionWith(dicCat3[30][list1[d]]);
  }
}

rand = 2 * RandString.Next(0 / 2, (dicCat[30].Count) / 2);
while (excludehash.Contains(rand))
{
  rand = 2 * RandString.Next(0 / 2, (dicCat[30].Count) / 2);
}
// action with random

在这种情况下,我使用 UnionWith() 方法来合并索引异常的 HashSet,而不是 AddRange()

奇怪的是,经过数千次迭代后 - List 方法的整体性能更好!,但根据许多消息来源,HashSet 应该执行得更快。性能分析器显示最大的性能消耗是 HashSet 的 UnionWith() 方法。

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

附言哈希集和列表检索自:

static Dictionary<int, Dictionary<int, HashSet<int>>> dicCat3;
static Dictionary<int, Dictionary<int, List<int>>> 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++;
   }
 }
}

最佳答案

尝试使用 SortedSet 而不是 HashSet。

关于c# - HashSet UnionWith()方法在C#中的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10551112/

相关文章:

javascript - 在 Web 方法中获取 JSON 数组中的数组?如何?

c# - 我如何在 C# 中反序列化 python pickles?

javascript - D3拖动事件触发的频率是多少?

python - 高效访问索引: is storing indices in a dict the fastest way?

c# - 我可以在没有 VS 的情况下创建自定义 Excel 文档级功能区吗

php - 下载多个网址的最快方法

c# - 在不先检查 InvokeRequired 的情况下更新 UI 时出现性能问题?

python-3.x - 更改列表中每个字典的特定键的值 - python

c# - 为什么调用我的 List<Point>.Clear() 会抛出 ArgumentOutOfRangeException?

c# - Adorner 会破坏 MVVM 吗?