skip to content

In .NET, how do SortedDictionary<TKey,TValue> and SortedList<TKey,TValue> differ in structure, insertion cost, memory and index access, and when does each win?

level: seniorimportance: should knowfreq 34%

answer

  1. a tree versus two arrays
  2. what binary search does not save
  3. keys arriving already in order
  4. reading by position

basics

~20 s

SortedDictionary<TKey,TValue> is a red-black tree: O(log n) insert and remove, one node object per entry, no index access. SortedList<TKey,TValue> is two sorted arrays: O(log n) lookup, O(n) insert or remove except at the end, less memory, index access.

solid answer

~40 s

Both keep keys ordered by an `IComparer<TKey>`, the key's own comparison by default, and look keys up in O(log n). `SortedDictionary<TKey,TValue>` wraps a red-black tree: insert and remove are O(log n) wherever the key lands, but each entry is a separate heap node with child pointers. `SortedList<TKey,TValue>` holds a keys array and a values array: `Add` binary-searches and then `Array.Copy`s everything after the insertion point, so random-order inserts are O(n) each, while ascending inserts cost only the search plus occasional growth. In exchange it is compact and indexable: `Keys[i]`, `GetKeyAtIndex`, `GetValueAtIndex`, `IndexOfKey`. Choose `SortedList` for data loaded once, mostly in order, then read or ranked by position; choose `SortedDictionary` for a long-lived map with frequent random inserts and removes.

code

csharp · 32 lines
csharp
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var rng = new Random(7);
int[] shuffled = Enumerable.Range(0, 20_000).OrderBy(_ => rng.Next()).ToArray();

var list = new SortedList<int, int>();
var tree = new SortedDictionary<int, int>();
long before = GC.GetAllocatedBytesForCurrentThread();
foreach (int k in shuffled) list.Add(k, k);          // binary search, then Array.Copy to open a gap
long listBytes = GC.GetAllocatedBytesForCurrentThread() - before;
before = GC.GetAllocatedBytesForCurrentThread();
foreach (int k in shuffled) tree.Add(k, k);          // one red-black tree node per entry
long treeBytes = GC.GetAllocatedBytesForCurrentThread() - before;
Console.WriteLine($"SortedList {listBytes:N0} B, SortedDictionary {treeBytes:N0} B");

Console.WriteLine($"{list.Keys[0]} {list.GetKeyAtIndex(19_999)} {list.IndexOfKey(500)}"); // 0 19999 500

var bins = new SortedDictionary<WarehouseBin, int>();  // no IComparable, no IComparer
try { bins.Add(new("A", 1, 4), 1); bins.Add(new("B", 1, 1), 2); }
catch (ArgumentException ex) { Console.WriteLine(ex.Message); }

var byLocation = new SortedDictionary<WarehouseBin, int>(Comparer<WarehouseBin>.Create((x, y) =>
{
    int c = string.CompareOrdinal(x.Aisle, y.Aisle);
    if (c != 0) return c;
    c = x.Shelf.CompareTo(y.Shelf);
    return c != 0 ? c : x.Slot.CompareTo(y.Slot);
}));
byLocation[new("B", 1, 1)] = 2; byLocation[new("A", 2, 9)] = 7; byLocation[new("A", 1, 4)] = 1;
Console.WriteLine(string.Join(" ", byLocation.Keys.Select(b => $"{b.Aisle}-{b.Shelf}-{b.Slot}")));

readonly record struct WarehouseBin(string Aisle, int Shelf, int Slot);

go deeper

for a junior

Recall that both types keep keys sorted, that SortedList is array-based with index access, and that SortedDictionary is a tree with no positions.

for a middle

Explain why SortedList inserts cost O(n) despite the binary search, why appending in order is cheap, and what each node of SortedDictionary costs in memory.

for a senior

Pick the type from the workload's insert pattern and read pattern, back the choice with an allocation count, and diagnose the run-time ArgumentException from a key with no comparer.

for a principal

Treat it as a local choice rather than a team standard, but require the comparer to be explicit for any domain key so ordering never depends on a type's default comparison.

## Same contract, different storage `SortedDictionary<TKey,TValue>` and `SortedList<TKey,TValue>` both implement `IDictionary<TKey,TValue>` and `IReadOnlyDictionary<TKey,TValue>`, reject duplicate and `null` keys, and enumerate in ascending key order. Neither hashes. Both find keys by **comparison**, using the `IComparer<TKey>` passed to the constructor or `Comparer<TKey>.Default`, which relies on the key implementing `IComparable<T>` or `IComparable`. Two keys are the same key when the comparer returns 0. What differs is the storage behind that contract. ## SortedList<TKey,TValue>: two parallel arrays - It keeps a `keys` array and a `values` array, both sorted by key, plus a count. - **Lookup** is `Array.BinarySearch` over the keys: O(log n). - **Add** binary-searches for the insertion point, then calls `Array.Copy` twice to shift every later key and value one place right. A random insertion moves about half the entries, so it is O(n). - **Appending** a key larger than all others shifts nothing, so loading data that arrives in ascending order costs O(log n) per insert plus array growth. Capacity starts at 4 on the first add and doubles; the `SortedList(int capacity)` constructor avoids the regrowth copies. - **Remove** shifts the tail left: O(n), except at the end. - **Index access** comes free from the arrays: `Keys[i]` and `Values[i]` through the `IList<TKey>` and `IList<TValue>` views, plus `GetKeyAtIndex`, `GetValueAtIndex`, `SetValueAtIndex`, `IndexOfKey`, `IndexOfValue` and `RemoveAt`. The `Keys` and `Values` views reject writes such as `Keys.Add` with `NotSupportedException`. ## SortedDictionary<TKey,TValue>: a red-black tree - It wraps a self-balancing **red-black tree** of `KeyValuePair<TKey,TValue>` items; the tree's height stays within about 2 log2(n + 1). - **Insert, lookup and remove** are all O(log n), wherever the key falls, with a few pointer re-links and recolourings on insert and remove. - **Memory**: every entry is its own heap object holding the pair, left and right child references and a colour. In the example, 20,000 `int`/`int` entries allocated 960,000 bytes, 48 bytes per node, against 524,952 bytes for `SortedList` including all its array regrowth. - **No index access**. Its `Keys` and `Values` are collections without an indexer; finding the 40th key means walking the tree in order. - **Enumeration** walks the tree with an explicit stack that the enumerator allocates. ## Side by side | | `SortedList<TKey,TValue>` | `SortedDictionary<TKey,TValue>` | |---|---|---| | Storage | two sorted arrays | red-black tree nodes | | Lookup | O(log n) | O(log n) | | Random insert or remove | O(n) shift | O(log n) | | Append in key order | O(log n) plus growth | O(log n) | | Memory | compact, contiguous | one object per entry | | Index access | yes | no | ## Reading the allocation numbers The measured figures follow from the structures, not from timing noise: - **SortedList**: the arrays grow 4, 8, 16, up to 32,768 slots. Each growth allocates a new key array and a new value array and abandons the old pair, so the total is roughly the final pair (2 x 32,768 x 4 bytes, about 262 KB) plus every smaller generation before it, about the same again, which matches the 524,952 bytes printed. - **SortedDictionary**: 20,000 nodes x 48 bytes is exactly the 960,000 bytes printed, and that memory stays live as long as the map does, spread across the heap in 20,000 separate objects. - Pre-sizing changes the first picture completely: `new SortedList<int, int>(20_000)` allocates its two arrays once, while a tree has no capacity to set. ## Choosing between them 1. Data built once, mostly in ascending key order, then read many times or addressed by rank: **`SortedList`**. It uses less memory and its arrays are friendly to the CPU cache. 2. A long-lived map that takes inserts and removes at random positions, such as a set of open orders keyed by price: **`SortedDictionary`**, because each change stays O(log n). 3. Unsure: measure with your real key distribution and count allocations with `GC.GetAllocatedBytesForCurrentThread()` around the load, rather than relying on one stopwatch run. ## The comparer requirement A key type with no `IComparable` and no supplied comparer compiles, because both types constrain `TKey` only to `notnull`. It fails at run time the first time two keys must be compared: adding a second `WarehouseBin` record struct to a `SortedDictionary<WarehouseBin, int>` throws `ArgumentException` with the message `At least one object must implement IComparable.` The fix is an `IComparer<WarehouseBin>`, for example from `Comparer<WarehouseBin>.Create`, passed to the constructor.

  • Why does loading pre-sorted data into SortedList<TKey,TValue> stay cheap?
    Each `Add` binary-searches, finds that the new key belongs after the last one, and `Array.Copy` has nothing to shift. What remains is the search and the occasional doubling of both arrays, which the `SortedList(int capacity)` constructor removes when you know the final count.
  • Why do sorted dictionaries take an IComparer<TKey> and not an IEqualityComparer<TKey>?
    They never hash. They place and find keys by ordering comparisons, and treat two keys as the same key when `Compare` returns 0. The comparer must therefore define a consistent total order, and two keys it ranks equal collide, so `Add` throws `ArgumentException` for the second.

SortedList is a ring binder with numbered pages: you can open page 40 directly, but slipping a new page into the middle means renumbering every page after it. SortedDictionary is a pile of index cards linked by smaller and larger pointers: adding a card anywhere re-links only a few, but nobody can hand you the 40th card without counting.

  • SortedList<TKey,TValue> is a linked list, so inserting anywhere is O(1).
  • SortedDictionary<TKey,TValue> supports index access such as Keys[i].
  • Both types hash their keys and only sort when you enumerate.
  • Random inserts into SortedList are O(log n) because it binary-searches.
  • A key type without IComparable fails to compile in SortedDictionary.