List< T> .Contains()很慢吗?

List< T> .Contains()很慢吗?

问题描述:

谁能解释我为什么泛型List.Contains()函数这么慢?

Could anyone explain me why the generics List.Contains() function is so slow?

我有一个带有大约一百万个数字的List<long>,并且代码会不断检查这些数字中是否有特定数字.

I have a List<long> with about a million numbers, and the code that is constantly checking if there's a specific number within these numbers.

我尝试使用Dictionary<long, byte>Dictionary.ContainsKey()函数执行相同的操作,它比使用List快10-20倍.

I tried doing the same thing using Dictionary<long, byte> and the Dictionary.ContainsKey() function, and it was about 10-20 times faster than with the List.

当然,我并不是真的想使用Dictionary,因为它不是那样使用的.

Of course, I don't really want to use Dictionary for that purpose, because it wasn't meant to be used that way.

所以,这里真正的问题是,除了List<T>.Contains()之外,还有其他选择吗?

So, the real question here is, is there any alternative to the List<T>.Contains(), but not as whacky as Dictionary<K,V>.ContainsKey() ?

如果仅检查是否存在,.NET 3.5中的HashSet<T>是最佳选择-类似字典的性能,但不提供键/值对-仅值:

If you are just checking for existence, HashSet<T> in .NET 3.5 is your best option - dictionary-like performance, but no key/value pair - just the values:

    HashSet<int> data = new HashSet<int>();
    for (int i = 0; i < 1000000; i++)
    {
        data.Add(rand.Next(50000000));
    }
    bool contains = data.Contains(1234567); // etc