我有许多包含不同索引异常的HashSet
。根据输入数据,我将这些hashset组合成一个大的HashSet
。为了测试目的,我还将HashSet
转换成List
类似物。
HashSet
和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)
,从而跳过UnionWith()
方法)P.S.哈希集和列表是从以下位置检索的:
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++;
}
}
}