我有许多包含不同索引异常的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
如您所见,所有异常(索引)都使用 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/