0

This question may have been asked in different formats, but for my current requirement can someone suggest which is the best..

In ASP.Net i have my own implementation of local & global resources, I'm storing the key value pair in static Dictionary object, Totally there may be a maximum of 10,000 values (all pages). When asp.net application loads a page it stores the value in my static dictionary object. When the page is visited again instead of reading the value from resource file it is served from static Dictionary object.

My question is for performance reason Dictionary is the best or should i go with SortedList/ SortedDictionary

user841683
  • 335
  • 6
  • 17
  • Why do you need sorting? If you always access the values via the key, there would be no advantage but only less performance since a SortedList **must reorder all indices on creating, inserting and deleting**. The only advantage is that you can access it via key or index and you get a correct sort order by key when you enumerate the DictionaryEntries. – Tim Schmelter Aug 20 '11 at 23:32
  • I don't need sorting, My thought was if record is stored in sorted order while fetching single value it will be faster. I'm not sure about the algorithm it uses inside – user841683 Aug 20 '11 at 23:47
  • 1
    It doesn't matter where it is stored in a Dictionary type. They are accessible directly through the key, it's like an address. Stay with the Dictionary. If you want more informations on the algorith, have a look at [this SO-answer](http://stackoverflow.com/questions/1427147/sortedlist-sorteddictionary-and-dictionary/1427158#1427158). – Tim Schmelter Aug 20 '11 at 23:59

1 Answers1

1

Sorting adds overhead, so if you don't need sorting, you're just looking up a single page from the dictionary based on key, then I would stick with the Dictionary.

From you scenario, I assume lookup speed is the most important concern.

SortedDictionary uses a red-black tree, a binary tree that keeps the collection ordered whenever an item is added/deleted. So if you're looking for ranges of values, where the location of one item in the collection relative to another item is important, then SortedDictionary makes sense. Where you might need to access the collection using an index (like an array) instead of the key, SortedList makes sense.

Dictionary uses a hash table to hash and store the keys, which it uses for lookups, so it makes looking up a random, single item very fast. This matches your scenario.

SortedDictionary operates on the order of O(log n) for add/lookup, where Dictionary operates on O(1) for add/lookup.

See a comparison of the System.Collections.Generic collections.

nekno
  • 19,177
  • 5
  • 42
  • 47
  • 1
    Sorting is done on add/insert/delete, but the backing store is a different mechanism that lends itself to different operations. I'll update my answer with details. – nekno Aug 20 '11 at 23:51