List< T> .Contains()很慢吗? [英] List<T>.Contains() is very slow?

查看:270
本文介绍了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

这篇关于List&lt; T&gt; .Contains()很慢吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆