Doing First () vs Last () in a SortedDictionary

I use SortedDictionaries to simulate a queue (due to some requirements that I have), and I call Last () on a sorted dictionary to get the item I need to delete.

I'm just curious about the performance of using custom mapping and calling First () or continue calling Last ().

After decompiling the .NET 3.5 assemblies, I found that the SortedDictionary class has the Count property, so I assume that the structure simply returns the element at position 0 when First is called, and the element at [count-1] when Last is called, am I right?

+4
source share
2 answers

No.

Since SortedDictionary does not implement IList<TValue> (which has the index this[int] ), Last() has no choice but to repeat all this.

+6
source

The last method is the extension method in the Enumerable class. The Last First implementation attempts to pass an IEnumerable (your SortedDictionary ) to IList<T> . If possible, it uses the Count property to directly access the last item. If he cannot, then he must go through all the elements to get to the last. SortedDictionary does not implement IList<T> , so Last will SortedDictionary over all elements.

+4
source

Source: https://habr.com/ru/post/1434281/


All Articles