C#中,列表与LT; T>。载() - 太慢? [英] C#, List<T>.Contains() - too slow?

查看:164
本文介绍了C#中,列表与LT; T>。载() - 太慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释我为什么泛型列表的载有()函数是如此之慢?
我有大约一百万数字的列表,和code表示被不断地检查,如果有,这些数字中的特定数字。
我试图做使用字典和使用containsKey()函数一样的东西,这是不是与列表快约10-20倍。
当然,我真的不希望使用词典的目的,因为它并不意味着要使用这种方式。
所以,真正的问题在这里,有没有替代List.Contains(),但不作为怪诞为Dictionary.ContainsKey()?
在此先感谢!

Could anyone explain me why the generics list's Contains() function is so slow?
I have a List with about a million numbers, and the code that is constantly checking if there's a specific number within these numbers.
I tried doing the same thing using Dictionary and the ContainsKey() function, and it was about 10-20 times faster than with the List.
Of course, I don't really want to use Dictionary for that purpose, because it wasn't meant to be used that way.
So, the real question here is, is there any alternative to the List.Contains(), but not as whacky as Dictionary.ContainsKey() ?
Thanks in advance!

推荐答案

如果你只是检查实存,的HashSet< T> 在.NET 3.5是你最好的选择 - 字典一样的性能,但是没有键/值对 - 只是值:

If you are just checking for existance, 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

这篇关于C#中,列表与LT; T&GT;。载() - 太慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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