我对Linq的Except
方法进行了基准测试,以克隆和使用HashSet本机函数ExceptWith
。结果如下。
static class Program
{
public static HashSet<T> ToSet<T>(this IEnumerable<T> collection)
{
return new HashSet<T>(collection);
}
public static HashSet<T> Subtract<T>(this HashSet<T> set, IEnumerable<T> other)
{
var clone = set.ToSet();
clone.ExceptWith(other);
return clone;
}
static void Main(string[] args)
{
var A = new HashSet<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var B = new HashSet<int> { 2, 4, 6, 8, 10 };
var sw = new Stopwatch();
sw.Restart();
for (int i = 0; i < 1000000; ++i)
{
var C = A.Except(B).ToSet();
}
sw.Stop();
Console.WriteLine("Linq: {0} ms", sw.ElapsedMilliseconds);
sw.Restart();
for (int i = 0; i < 1000000; ++i)
{
var C = A.Subtract(B);
}
sw.Stop();
Console.WriteLine("Native: {0} ms", sw.ElapsedMilliseconds);
Console.ReadLine();
}
}
的Linq:1297毫秒
本机:762毫秒
http://programanddesign.com/cs/subtracting-sets/
你的意思是你想知道如何克隆哈希集合? – kennytm 2010-10-09 19:37:39
@KennyTM:我的意思是我想知道如何完成工作。如果这意味着克隆,那么是的,如果有更好的方法,那么不。 – mpen 2010-10-09 19:46:24