c# - HashSet<int> 和 List<int> 的快速交集

标签 c# algorithm performance intersection hashset

我有一个 HashSet<int>和一个 List<int> (Hashset 大约有 300 万个项目,List 大约有 300k 个项目)。

我目前使用它们相交

var intersected = hashset.Intersect(list).ToArray();

我想知道是否有更快的方法来做到这一点。也许并行?

最佳答案

HashSet有一个方法 IntersectWith optimized if intersection is performed between two hash sets .使用方法IntersectWith我们可以相交HashSetList使用下一个方法:

private static IEnumerable<int> Intersect(HashSet<int> hash, List<int> list)
{
    HashSet<int> intersect = new HashSet<int>(list);
    intersect.IntersectWith(hash);
    return intersect;
}

我已经测量(使用 Stopwatch )您的原始方法( Linq Intersect )、@TheodorZoulias 提出的方法( HashSet Contains and HashSet Contains Parallel )和我的方法( HashSet IntersectWith )的性能。以下是结果:
------------------------------------------------------------------------
|         Method            | Min, ms | Max, ms | Avg, ms | StdDev, ms |
------------------------------------------------------------------------
| Linq Intersect            |   135   |   274   |   150   |     17     |
| HashSet Contains          |    25   |    44   |    26   |      2     |
| HashSet Contains Parallel |    12   |    53   |    13   |      3     |
| HashSet IntersectWith     |    57   |    89   |    61   |      4     |
------------------------------------------------------------------------

从表中我们可以看出最快的方法是HashSet Contains Parallel最慢的是Linq Intersect .

这是complete source code这是用来衡量性能的。

关于c# - HashSet<int> 和 List<int> 的快速交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61547382/

相关文章:

c# - 上传HTTP进度跟踪

c++ - 不同线程上的动态分配会减慢我的主处理线程吗?

c# - 如何对某些 StyleCop 规则进行异常(exception)处理?

c# - 按需转换集合包装器

arrays - 从两组中找到元素的所有组合,以使它们的几何均值落入第三组

java - 如何获得数组中某个重复出现的数字的一组频率?

angular - 如何在 Angular 7 中使用 typescript 获取属性值

c++ - 随着时间的推移,我的程序变慢了,我不知道为什么。内存泄漏?

java - 如何在java中的循环中初始化数组?

c# - 将 x 个周期添加到 DateTime