which is best to use ? List or Dictionary ? For efficiency of code execution.

来源:互联网 发布:江苏普通发票软件 编辑:程序博客网 时间:2024/06/07 06:58

Question

  • Question
    Sign in to vote
    0
    Sign in to vote

    which is best to use  ? List or Dictionary ? For efficiency of code execution.


    Dipak Patel
    Wednesday, July 13, 2011 6:50 AM
    Avatar of Patel Dipak
    Patel Dipak
    5 Points

Answers

  • Question
    Sign in to vote
    2
    Sign in to vote

    Like others have said, the answer is "it depends".

    Lists are by far the fastest for adding a bunch of items, but dictionaries are faster for looking them up. Hashsets provide the best lookup performance, and are slightly faster for adding than dictionaries.

    In general, I use them for different purposes.

    1. List<T> is great when you are not guaranteed to have a unique key for each item added and order is important. If you need to be able to get myList[10] and have that return the 10th item added, List is the one for you.
    2. Dictionary<TKey, TValue> is best when each item in the list is guaranteed to have a unique key. Adding and fetching are both faster than a List<T> because of the key, but it does not allow the same key to be used twice, and it imposes no order - you can't iterate over the Dictionary "in order" because there is no order.
    3. HashSet<T> is great if you just need to store some collection of items, but you don't care about the order and you never need to iterate over them individually.  You can use LINQ expressions to work with the set as a whole, but it's meaningless to use mySet[10] because the items aren't stored in any order.

    Last and most importantly: before spending a lot of time on things like this, make sure it matters. Performance for all of these classes is counted in terms of milliseconds. The vast majority of the time, your application's bottleneck will be caused by disk read/writes, network traffic, or user interaction. Make sure those other areas of your system are flawless before you worry too much about the performance of your in-memory data structures. Start witht he most bang for the buck, and you will only need to worry about stuff like this when performance is absolutely critical. And, in those cases, chances are you'll want to build a more full-fledged data structure to meet your needs anyway, and the structure you build on top of these collections will matter more than which collection you choose. For example, if ordering is important and performance is critical, you'll probably want to create a Skip List rather than relying on the generic List<T> class.

0 0
原创粉丝点击