Search code examples
c#dictionarybenchmarkingsorteddictionary

when should I use a sorteddictionary instead of a dictionary


As I wrote in some of my last posts I am still quite new to the c# world so it comes that I wrote small benchmark to compare Dictionary, Hashtable, SortedList and SortedDictionary against each other. The test runs with 8000 iterations and from 50 to 100000 elements. I tested adding of new elements, search for elements and looping through some elements all random. The results was as I expected them to be except the result of the SortedDictionary which was much confusing for me... It was just slow in all results. So did I missing sometging about the concept of a sorted dictionary. I already asked google but All that I found out was that others had come to the same test result. Slightly different based on their implementation of the test. Again my question: why is the SortedDicrionary so much slower than all the others?


Solution

  • A SortedDictionary is implemented as a binary search tree. Therefore, accessing an element is O(lg(n)). A Dictionary is a hash table, and has a complexity of O(1) for access.

    A SortedDictionary is quite useful when you need the data to be sorted (a Dictionary has no defined order). Dictionary is appropriate for most cases.