Search code examples
performancelinq.net-3.5sorteddictionary

Performance of First() vs Last() on a SortedDictionary


I'm using SortedDictionaries to simulate a Queue (due to some requirements that I have), and I'm calling Last() over the sorted dictionary to get the item that I need to dequeue.

I was just wondering about the performance of using a custom comparer and calling First() or keep calling Last().

After decompiling the .NET 3.5 assemblies, I found that the SortedDictionary class does have a Count property, so I'm guessing the framework just returns the item at position 0 when First is called, and the item at position [count-1] when Last is called, am I right?


Solution

  • No.

    Since SortedDictionary does not implement IList<TValue> (which has a this[int] indexer), Last() has no choice but to iterate through the whole thing.