在比较两个列表中的项目时,我有哪些选项?我遇到了一些性能问题,我想知道是否有更快的替代方案:
int[] foo = { 1, 2, 3, 4, 5 };
int[] bar = { 6, 7, 8, 9, 1 };
var result = foo.Any(x => bar.Contains(x));
无论我使用lambda方法还是自己使用foreach
,我都认为性能损失仍为O(N^2)
。我能做些什么影响吗?
答案 0 :(得分:6)
您可以使用Enumerable.Intersect:
var result = foo.Intersect(bar).Any();
从Set<T>
项创建bar
,然后枚举foo
,直到找到第一个匹配项。内部看起来像:
Set<int> set = new Set<int>();
foreach (int local in bar) // M times
set.Add(local); // O(1)
foreach (int value in foo) // N times max
{
if (!set.Remove(value)) // O(1)
continue;
yield return value;
}
正如PatrykĆwiek正确指出的那样,给你O(N + M)而不是O(N * M)
答案 1 :(得分:2)
您可以使用Hashset:
int[] foo = { 1, 2, 3, 4, 5 };
int[] bar = { 6, 7, 8, 9, 1 };
var hashSet = new Hashset<int>(bar);
var result = foo.Any(x => hashSet.Contains(x));
或者您可以将Except
与Any一起使用:
var result = !foo.Except(bar).Any();
我打赌那是与Sergey's solution:p
比赛答案 2 :(得分:2)
为了完整起见,这是一个基准程序,用于测试该线程中的各种答案。
似乎表明HashSet方法略微快:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Demo
{
internal class Program
{
private void run()
{
var foo = Enumerable.Range( 0, 100000).ToArray();
var bar = Enumerable.Range(100000, 100000).ToArray();
int trials = 4;
Stopwatch sw = new Stopwatch();
for (int i = 0; i < trials; ++i)
{
sw.Restart();
method1(foo, bar);
Console.WriteLine("method1() took " +sw.Elapsed);
sw.Restart();
for (int j = 0; j < 100; ++j)
method2(foo, bar);
Console.WriteLine("method2()*100 took " +sw.Elapsed);
sw.Restart();
for (int j = 0; j < 100; ++j)
method3(foo, bar);
Console.WriteLine("method3()*100 took " +sw.Elapsed);
Console.WriteLine();
}
}
private static bool method1(int[] foo, int[] bar)
{
return foo.Any(bar.Contains);
}
private static bool method2(int[] foo, int[] bar)
{
var hashSet = new HashSet<int>(bar);
return foo.Any(hashSet.Contains);
}
private static bool method3(int[] foo, int[] bar)
{
return foo.Intersect(bar).Any();
}
private static void Main()
{
new Program().run();
}
}
}
我的电脑上的结果(发布版本)如下。请注意,我每次运行method2()和method3()100次,因为它们比method1()快得多:
method1() took 00:00:12.2781951
method2()*100 took 00:00:00.4920760
method3()*100 took 00:00:00.7045298
method1() took 00:00:11.9267980
method2()*100 took 00:00:00.4688330
method3()*100 took 00:00:00.6886865
method1() took 00:00:11.8959856
method2()*100 took 00:00:00.4736563
method3()*100 took 00:00:00.6875508
method1() took 00:00:11.9083229
method2()*100 took 00:00:00.4572404
method3()*100 took 00:00:00.6838919