When to use a SortedList over a SortedDictionary?

后端 未结 6 501
梦毁少年i
梦毁少年i 2020-11-29 01:50

This may appear to be a duplicate of this question, which asks \"What’s the difference between SortedList and SortedDictionary?\" Unfortunately, the answers do nothing more

6条回答
  •  鱼传尺愫
    2020-11-29 02:08

    I don't know why MSDN says that SortedList use a binary tree for its implementation because if you look at code with a decompiler like Reflector you realize its not true.

    SortedList is simply an array that grows over the time.

    Every time you insert an element, it first check if the array has enough capacity, if not, a bigger array is recreated and old elements are copied into it (like List)

    After that, it searches where to insert the element, using a binary search (this is possible since the array is indexable and already sorted).

    To keep the array sorted, it moves (or pushes) all the elements situated after position of element to be inserted by one position (using Array.Copy()).

    Eg :

    // we want to insert "3" 
    
    2  
    4  <= 3
    5
    8
    9
    .      
    .      
    .  
    
    // we have to move some elements first
    
    2
    .  <= 3
    4 
    5  |
    8  v
    9
    .
    .
    

    That explains why performance of SortedList is so bad when you insert unsorted elements. It has to re-copy some elements almost every insertion. The only case it has not to be done is when the element has to be inserted at the end of the array.

    SortedDictionary is different and use a binary tree to insert and retrieve elements. It also has some cost at insert because sometimes the tree need to be re-balanced (but not every insertion).

    Performance is quite similar while searching an element with SortedList or SortedDictionary because they both use a binary search.


    In my opinion, you should never use SortedList to just sort an array. Unless you have very few elements, it will always be faster to insert values into a list (or array) and then call Sort() method.

    SortedList is mostly useful when you have a list of values already sorted (eg: from database), you want to keep it sorted and perform some operations that would take advantage it is sorted (eg: Contains() method of SortedList performs a binary search instead of linear search)

    SortedDictionary offers same advantages than SortedList but performs better if values to insert are not already sorted.


    EDIT : If you are using .NET Framework 4.5, an alternative to SortedDictionary is SortedSet. It works the same way as SortedDictionary, using a binary tree, but keys and values are the same here.

提交回复
热议问题