When to use a SortedList over a SortedDictionary?

后端 未结 6 496
梦毁少年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:33

    I'm not sure how accurate the MSDN documentation is on SortedList and SortedDictionary. It seems to be saying both are implemented using a binary search tree. But if the SortedList uses a binary search tree, why would it be much slower on additions than SortedDictionary?

    Anyway, here are some performance test results.

    Each test operates on a SortedList / SortedDictionary containing 10,000 int32 keys. Each test is repeated 1,000 times (Release build, Start without Debugging).

    The first group of tests add keys in sequence from 0 to 9,999. The second group of tests add random shuffled keys between 0 to 9,999 (every number is added exactly once).

    ***** Tests.PerformanceTests.SortedTest
    
    SortedDictionary Add sorted: 4411 ms
    SortedDictionary Get sorted: 2374 ms
    
    
    SortedList Add sorted: 1422 ms
    SortedList Get sorted: 1843 ms
    
    ***** Tests.PerformanceTests.UnsortedTest
    
    SortedDictionary Add unsorted: 4640 ms
    SortedDictionary Get unsorted: 2903 ms
    
    
    SortedList Add unsorted: 36559 ms
    SortedList Get unsorted: 2243 ms
    

    As with any profiling, the important thing is the relative performance, not the actual numbers.

    As you can see, on sorted data the sorted list is faster than the SortedDictionary. On unsorted data the SortedList is slightly quicker on retrieval, but about 9 times slower on adding.

    If both are using binary trees internally, it is quite surprising that the Add operation on unsorted data is so much slower for SortedList. It is possible that sorted list may also be adding items to a sorted linear data structure at the same time, which would slow it down.

    However, you would expect the memory usage of a SortedList to be equal or greater than or at least equal to a SortedDictionary. But this contradicts what the MSDN documentation says.

提交回复
热议问题