New collection types: PriorityQueue, FrozenDictionary, OrderedDictionary and SearchValues
suggest changeFor about 15 years the collections in System.Collections.Generic barely changed: List<T>, Dictionary<TKey,TValue>, HashSet<T>, Queue<T>, Stack<T>, the sorted collections, and later the immutable collections. Recent .NET versions added several new types, each built for one job:
| Type | Since | Use it for |
|---|---|---|
PriorityQueue<TElement,TPriority> |
.NET 6 | taking the item with the smallest priority next (schedulers, Dijkstra, top-K) |
FrozenDictionary<TKey,TValue>, FrozenSet<T> |
.NET 8 | lookup tables that are built once and read many times |
SearchValues<T> |
.NET 8 (strings in .NET 9) | fast IndexOfAny / ContainsAny for a fixed set of chars, bytes or strings |
OrderedDictionary<TKey,TValue> |
.NET 9 | a dictionary that remembers insertion order and supports access by index |
alternate lookup (GetAlternateLookup<ReadOnlySpan<char>>) |
.NET 9 | looking up string keys with a ReadOnlySpan<char>, without allocating a string |
The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs. For the classic collections, see Overview of C# collections and Dictionary<TKey,TValue>.
PriorityQueue: always take the most urgent item
A Queue<T> returns items in the order they were added. A PriorityQueue<TElement, TPriority> returns the item with the lowest priority value first, no matter when it was added:
var pq = new PriorityQueue<string, int>();
pq.Enqueue("write docs", 3);
pq.Enqueue("fix crash", 1);
pq.Enqueue("refactor", 5);
pq.Enqueue("review PR", 2);
Console.WriteLine($"Count: {pq.Count}, next: {pq.Peek()}");
while (pq.TryDequeue(out string? task, out int priority))
{
Console.WriteLine($"{priority}: {task}");
}
Count: 4, next: fix crash
1: fix crash
2: review PR
3: write docs
5: refactor
The priority is stored next to the element, not computed from it, so the same object can be added several times with different priorities. Internally it's an array-backed binary heap (4-ary, to be exact): Enqueue and Dequeue are O(log n), Peek is O(1).
Things that surprise people:
- It's a min-queue. To get the largest priority first, pass a reversed comparer.
- It's not stable. Items with equal priority come out in no particular order. If you need FIFO order among equal priorities, add a sequence number to the priority.
UnorderedItemsis in heap order. Enumerating it doesn't sort anything.PriorityQueueitself doesn't implementIEnumerable<T>for that reason.- There's no "update priority".
Remove(.NET 9) exists but is O(n).
// Max-heap: reverse the comparer
var maxQ = new PriorityQueue<string, int>(Comparer<int>.Create((a, b) => b.CompareTo(a)));
maxQ.EnqueueRange([("low", 1), ("high", 9), ("mid", 5)]);
Console.WriteLine(string.Join(", ", Drain(maxQ)));
// Same priority: order is not guaranteed
var ties = new PriorityQueue<string, int>();
foreach (var name in new[] { "a", "b", "c", "d", "e", "f" })
ties.Enqueue(name, 1);
Console.WriteLine(string.Join(", ", Drain(ties)));
// Make it FIFO for equal priorities with a sequence number
var fifo = new PriorityQueue<string, (int Priority, long Seq)>();
long seq = 0;
foreach (var name in new[] { "a", "b", "c", "d", "e", "f" })
fifo.Enqueue(name, (1, seq++));
Console.WriteLine(string.Join(", ", Drain(fifo)));
// Remove (.NET 9) is O(n)
var q = new PriorityQueue<string, int>([("x", 3), ("y", 1), ("z", 2), ("w", 0)]);
bool removed = q.Remove("z", out string? r, out int rp);
Console.WriteLine($"removed {r}:{rp} = {removed}, left {string.Join(", ", Drain(q))}");
static List<T> Drain<T, P>(PriorityQueue<T, P> q)
{
var list = new List<T>();
while (q.TryDequeue(out T? item, out _)) list.Add(item);
return list;
}
high, mid, low
a, f, e, d, c, b
a, b, c, d, e, f
removed z:2 = True, left w, y, x
Tuples compare element by element, so (1, 0) comes before (1, 1): the sequence number breaks ties in insertion order.
And here is UnorderedItems showing the heap layout rather than sorted order:
var q = new PriorityQueue<string, int>();
foreach (var (item, prio) in new[] { ("a", 5), ("b", 4), ("c", 3), ("d", 2), ("e", 1) })
q.Enqueue(item, prio);
foreach (var (item, prio) in q.UnorderedItems)
Console.Write($"{item}:{prio} ");
Console.WriteLine();
e:1 a:5 b:4 c:3 d:2
Top-K with DequeueEnqueue
To find the K largest items in a big or endless stream, keep a min-heap of size K. Its smallest element is the bar a new item must beat. DequeueEnqueue removes the smallest and adds the new item in one operation, which is cheaper than calling Dequeue and then Enqueue:
// The 3 largest numbers from a stream, using a min-heap of size 3
int[] data = [42, 7, 93, 15, 88, 3, 61, 99, 24, 70];
const int K = 3;
var heap = new PriorityQueue<int, int>(K);
foreach (int n in data)
{
if (heap.Count < K)
heap.Enqueue(n, n);
else if (n > heap.Peek())
heap.DequeueEnqueue(n, n); // remove smallest, add n: one sift
}
var top = heap.UnorderedItems.Select(x => x.Element).OrderDescending();
Console.WriteLine(string.Join(", ", top));
99, 93, 88
Memory stays O(K) and time is O(n log K), compared with O(n log n) for sorting everything. There's also EnqueueDequeue, which adds first and then removes the smallest. It returns the new item right away if it's smaller than everything in the queue.
Dijkstra's shortest path
The textbook use. Because the queue has no "decrease priority" operation, the usual trick is to enqueue the node again with the better distance and skip stale entries when they come out:
var graph = new Dictionary<string, (string To, int Cost)[]>
{
["A"] = [("B", 4), ("C", 1)],
["C"] = [("B", 2), ("D", 7)],
["B"] = [("D", 1)],
["D"] = [],
};
var dist = new Dictionary<string, int> { ["A"] = 0 };
var prev = new Dictionary<string, string>();
var queue = new PriorityQueue<string, int>();
queue.Enqueue("A", 0);
while (queue.TryDequeue(out string? node, out int d))
{
if (d > dist[node]) continue; // stale entry, a shorter path was found later
foreach (var (to, cost) in graph[node])
{
int nd = d + cost;
if (nd < dist.GetValueOrDefault(to, int.MaxValue))
{
dist[to] = nd;
prev[to] = node;
queue.Enqueue(to, nd); // no decrease-key: just add a new entry
}
}
}
var path = new List<string> { "D" };
while (prev.TryGetValue(path[^1], out string? p)) path.Add(p);
path.Reverse();
Console.WriteLine($"A -> D: {string.Join(" -> ", path)}, cost {dist["D"]}");
A -> D: A -> C -> B -> D, cost 4
PriorityQueue is not thread-safe. For producer/consumer work across threads, protect it with a lock or use a channel instead.
FrozenDictionary and FrozenSet: pay once, read fast
A lot of dictionaries are filled at startup and never change again: configuration, keyword tables, MIME types, routing tables, feature flags. System.Collections.Frozen (.NET 8) is made for exactly that. You create a frozen collection from any sequence with ToFrozenDictionary or ToFrozenSet. Creating it is slower than creating a Dictionary, because it analyzes the keys and picks a layout and hash strategy that suit them. Lookups afterwards are as fast as Dictionary or faster.
using System.Collections.Frozen;
var source = new Dictionary<string, int>
{
["http"] = 80,
["https"] = 443,
["ssh"] = 22,
};
FrozenDictionary<string, int> ports = source.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
FrozenSet<string> secure = new[] { "https", "ssh" }.ToFrozenSet();
Console.WriteLine(ports["HTTPS"]);
Console.WriteLine(ports.TryGetValue("ftp", out int p) ? p : -1);
Console.WriteLine(secure.Contains("ssh"));
// Changing the source doesn't affect the frozen copy
source["ftp"] = 21;
Console.WriteLine($"{source.Count} vs {ports.Count}");
// Keys and Values are ImmutableArray<T>
Console.WriteLine(ports.Keys.GetType().Name);
Console.WriteLine(string.Join(", ", ports.Keys));
// The IDictionary<K,V> mutators throw
IDictionary<string, int> asDict = ports;
try { asDict["ftp"] = 21; }
catch (NotSupportedException e) { Console.WriteLine($"{e.GetType().Name}: {e.Message}"); }
// Collection expressions work for FrozenSet (C# 12)
FrozenSet<int> primes = [2, 3, 5, 7];
Console.WriteLine(primes.Contains(5));
443
-1
True
4 vs 3
ImmutableArray`1
http, https, ssh
NotSupportedException: Specified method is not supported.
True
A frozen collection is a copy: once built, nothing can change it, so any number of threads can read it without locks. To "update" it, build a new one and swap the reference. That's the immutable snapshot pattern described in Race conditions. FrozenSet<T> supports collection expressions through [CollectionBuilder].
What "analyzes the keys" means
FrozenDictionary<TKey,TValue> is an abstract class. ToFrozenDictionary returns one of many internal subclasses, depending on the key type, the comparer and the keys themselves. You can see that by printing the runtime type:
using System.Collections.Frozen;
static string N(object o) { var t = o.GetType(); return t.DeclaringType is null ? t.Name : t.DeclaringType.Name + "+" + t.Name; }
Console.WriteLine(N(new Dictionary<int, string> { [1] = "a", [2] = "b" }.ToFrozenDictionary()));
Console.WriteLine(N(Enumerable.Range(0, 1000).ToDictionary(i => i, i => "x").ToFrozenDictionary()));
Console.WriteLine(N(new[]{"apple","banana","cherry"}.ToFrozenSet()));
Console.WriteLine(N(Enumerable.Range(0, 1000).Select(i => "key" + i).ToFrozenSet()));
Console.WriteLine(N(new[]{"a","b"}.ToFrozenSet(StringComparer.OrdinalIgnoreCase)));
DenseIntegralFrozenDictionary+WithOptionalValues`3
DenseIntegralFrozenDictionary+WithFullValues`3
LengthBucketsFrozenSet
OrdinalStringFrozenSet_RightJustifiedSubstring
LengthBucketsFrozenSet
Dense integer keys become a plain array indexed by key. Short string sets are bucketed by length, so most lookups are rejected without hashing. For longer strings it looks for the shortest substring that tells all keys apart and hashes only that substring (here the last few characters of key0...key999). These are implementation details that change between releases, but they explain why the frozen collections cost more to build.
Construction cost vs lookup speed
A small benchmark with BenchmarkDotNet: a set of 50 C# keywords with a case-insensitive comparer, and 100 lookups per call (50 hits in upper case, 50 misses). BenchmarkDotNet runs from a file-based app with three tweaks: reference the package, turn off Native AOT (on by default for file-based apps), and run the benchmarks in-process:
#:package BenchmarkDotNet@0.15.4
#:property PublishAot=false
using System.Collections.Frozen;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<KeywordLookup>();
[MemoryDiagnoser, InProcess]
public class KeywordLookup
{
static readonly string[] Keywords =
[
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked",
"class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum",
"event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto",
"if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace",
"new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public",
];
// half hits (in different case), half misses
readonly string[] _words = Keywords.Select(k => k.ToUpperInvariant())
.Concat(Keywords.Select(k => k + "x")).ToArray();
HashSet<string> _hash = null!;
FrozenSet<string> _frozen = null!;
[GlobalSetup]
public void Setup()
{
_hash = new HashSet<string>(Keywords, StringComparer.OrdinalIgnoreCase);
_frozen = Keywords.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
}
[Benchmark]
public HashSet<string> BuildHashSet() => new(Keywords, StringComparer.OrdinalIgnoreCase);
[Benchmark]
public FrozenSet<string> BuildFrozenSet() => Keywords.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
[Benchmark]
public int HashSet() { int n = 0; foreach (var w in _words) if (_hash.Contains(w)) n++; return n; }
[Benchmark]
public int FrozenSet() { int n = 0; foreach (var w in _words) if (_frozen.Contains(w)) n++; return n; }
}
Run it with dotnet run -c Release app.cs. Here are the Mean and Allocated columns from one run on .NET 10:
| Method | Mean | Allocated |
|--------------- |-----------:|----------:|
| BuildHashSet | 550.2 ns | 1296 B |
| BuildFrozenSet | 3,265.5 ns | 7216 B |
| HashSet | 812.9 ns | - |
| FrozenSet | 568.8 ns | - |
The machine was running other work at the same time, so treat the absolute numbers as rough and look at the ratios. Building the frozen set took about 6 times longer and allocated more memory. After that, each lookup was about 30% faster. At roughly 2.4 ns saved per lookup and about 2.7 µs of extra build time, the frozen set pays for itself after about a thousand lookups. A table built at startup and used on every request passes that point almost right away.
The gain depends on the keys. In another run, with 1,000 keys of the form key-0...key-999 and the default ordinal comparer, Dictionary and FrozenDictionary lookups were the same within measurement noise, and building the frozen dictionary took about 7 times longer than new Dictionary<,>(pairs). ImmutableDictionary (a balanced tree) was the slowest at both building and lookups. Measure with your real keys before you decide.
Rules of thumb:
- Use frozen collections for data that's created once and read for the lifetime of the process, typically stored in a
static readonlyfield. - Don't use them for data that changes, or for collections you build, use a few times and throw away. Construction cost dominates there.
- If you need cheap "modified copies", use immutable collections instead. A frozen collection can only be rebuilt from scratch.
SearchValues: precomputed sets for IndexOfAny
IndexOfAny finds the first character that belongs to a set. The runtime vectorizes it, but it has to inspect the set on every call to choose a strategy. SearchValues<T> (System.Buffers, .NET 8) does that analysis once, up front, and stores the result. You create one with SearchValues.Create, keep it in a static readonly field, and pass it to the span methods IndexOfAny, IndexOfAnyExcept, LastIndexOfAny, ContainsAny and ContainsAnyExcept:
using System.Buffers;
string path = "reports/2026/q3 summary?.pdf";
Console.WriteLine(Validator.FirstInvalid(path));
Console.WriteLine(Validator.IsSafe("reports/2026/q3-summary.pdf"));
Console.WriteLine(Validator.FirstNonDigit("2026-10-18"));
static class Validator
{
// Build once, reuse forever: store SearchValues in a static readonly field
private static readonly SearchValues<char> Invalid = SearchValues.Create(" ?*:<>|\"");
private static readonly SearchValues<char> Digits = SearchValues.Create("0123456789");
public static int FirstInvalid(ReadOnlySpan<char> s) => s.IndexOfAny(Invalid);
public static bool IsSafe(ReadOnlySpan<char> s) => !s.ContainsAny(Invalid);
public static int FirstNonDigit(ReadOnlySpan<char> s) => s.IndexOfAnyExcept(Digits);
}
15
True
4
A string converts to ReadOnlySpan<char> implicitly, so you can pass strings to these methods directly.
.NET 9 added SearchValues<string>, which finds the first occurrence of any of several substrings in one pass. It accepts StringComparison.Ordinal or OrdinalIgnoreCase. SearchValues<byte> does the same for single bytes in UTF-8 or binary data:
using System.Buffers;
SearchValues<string> banned = SearchValues.Create(
["password", "secret", "api_key"], StringComparison.OrdinalIgnoreCase);
string[] lines =
[
"user=alice level=info",
"set API_KEY=abc123",
"Secret santa list updated",
];
foreach (string line in lines)
{
int i = line.AsSpan().IndexOfAny(banned);
Console.WriteLine(i < 0 ? $"ok: {line}" : $"redact: {line} (at {i})");
}
// bytes work too: find the first CR or LF in UTF-8 data
SearchValues<byte> newline = SearchValues.Create("\r\n"u8);
ReadOnlySpan<byte> data = "GET / HTTP/1.1\r\nHost: x\r\n"u8;
Console.WriteLine(data.IndexOfAny(newline));
ok: user=alice level=info
redact: set API_KEY=abc123 (at 4)
redact: Secret santa list updated (at 0)
14
How much faster is it?
The benchmark searches a 10,000-character string that contains no match (the worst case: every character is checked), and a 14-character file name:
#:package BenchmarkDotNet@0.15.4
#:property PublishAot=false
using System.Buffers;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<Search>();
[MemoryDiagnoser, InProcess]
public class Search
{
const string InvalidChars = " ?*:<>|\"";
static readonly char[] InvalidArray = InvalidChars.ToCharArray();
static readonly SearchValues<char> Invalid = SearchValues.Create(InvalidChars);
static readonly string[] Banned = ["password", "secret", "api_key"];
static readonly SearchValues<string> BannedValues =
SearchValues.Create(Banned, StringComparison.OrdinalIgnoreCase);
// 10,000 characters of text with no match
readonly string _text = string.Concat(Enumerable.Repeat("lorem-ipsum_dolor.sit/amet", 400));
readonly string _short = "q3-summary.pdf";
[Benchmark]
public int CharLoop()
{
string s = _text;
for (int i = 0; i < s.Length; i++)
if (InvalidChars.Contains(s[i])) return i;
return -1;
}
[Benchmark] public int IndexOfAnyArray() => _text.IndexOfAny(InvalidArray);
[Benchmark] public int IndexOfAnySearchValues() => _text.AsSpan().IndexOfAny(Invalid);
[Benchmark] public int ShortIndexOfAnyArray() => _short.IndexOfAny(InvalidArray);
[Benchmark] public int ShortIndexOfAnySearchValues() => _short.AsSpan().IndexOfAny(Invalid);
[Benchmark]
public int StringsIndexOfEach()
{
int best = -1;
foreach (string b in Banned)
{
int i = _text.IndexOf(b, StringComparison.OrdinalIgnoreCase);
if (i >= 0 && (best < 0 || i < best)) best = i;
}
return best;
}
[Benchmark] public int StringsSearchValues() => _text.AsSpan().IndexOfAny(BannedValues);
}
Mean times from one run on .NET 10 (nothing allocated in any of them):
| Method | Mean |
|---------------------------- |------------:|
| CharLoop | 8,519.75 ns |
| IndexOfAnyArray | 218.86 ns |
| IndexOfAnySearchValues | 217.09 ns |
| ShortIndexOfAnyArray | 10.04 ns |
| ShortIndexOfAnySearchValues | 0.98 ns |
| StringsIndexOfEach | 1,596.14 ns |
| StringsSearchValues | 654.18 ns |
What this shows:
- A hand-written loop is about 40 times slower than either vectorized version. Don't write one.
- On a long input,
IndexOfAny(char[])with a small ASCII set is as fast asSearchValues, because modern .NET builds the same kind of lookup table on every call. Once the input is long, that setup cost doesn't matter. - On a short input, the setup dominates.
SearchValueswas about 10 times faster on a 14-character string. Short inputs are the common case: file names, header values, identifiers, tokens. SearchValues<string>scanned the text once instead of three times and was about 2.4 times faster than threeIndexOfcalls. The advantage grows with the number of strings.
The source generator for [GeneratedRegex] uses SearchValues in the code it generates for character classes, so regular expressions benefit too.
OrderedDictionary<TKey,TValue>: insertion order and indexes
Dictionary<TKey,TValue> doesn't promise any order. It often looks like insertion order, which is why code ends up relying on it by accident, until a removal reuses a free slot:
var d = new Dictionary<string, int>();
var od = new OrderedDictionary<string, int>();
foreach (var key in new[] { "a", "b", "c", "d" }) { d[key] = 0; od[key] = 0; }
d.Remove("b"); od.Remove("b");
d["e"] = 0; od["e"] = 0;
Console.WriteLine($"Dictionary: {string.Join(", ", d.Keys)}");
Console.WriteLine($"OrderedDictionary: {string.Join(", ", od.Keys)}");
Dictionary: a, e, c, d
OrderedDictionary: a, c, d, e
OrderedDictionary<TKey,TValue> (.NET 9, in System.Collections.Generic) keeps entries in insertion order and also lets you work with them by index. It fits things where order matters: HTTP headers, form fields, JSON objects you round-trip, columns of a table, menu items.
var headers = new OrderedDictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["Host"] = "example.com",
["Accept"] = "*/*",
["User-Agent"] = "demo/1.0",
};
headers.Insert(0, "Connection", "close"); // at a position
headers["accept"] = "application/json"; // update keeps the position
headers.Add("Cache-Control", "no-cache"); // appended at the end
foreach (var (name, value) in headers)
Console.WriteLine($"{name}: {value}");
Console.WriteLine();
Console.WriteLine(headers.IndexOf("Host"));
var (k, v) = headers.GetAt(2);
Console.WriteLine($"{k} = {v}");
headers.SetAt(2, "text/html"); // replace the value at index 2
Console.WriteLine(headers["Accept"]);
headers.RemoveAt(0); // remove by index
Console.WriteLine(string.Join(", ", headers.Keys));
Connection: close
Host: example.com
Accept: application/json
User-Agent: demo/1.0
Cache-Control: no-cache
1
Accept = application/json
text/html
Host, Accept, User-Agent, Cache-Control
.NET 10 adds overloads that also return the index, which saves a second lookup:
var od = new OrderedDictionary<string, int> { ["a"] = 1, ["b"] = 2 };
Console.WriteLine(od.TryAdd("b", 5, out int index) + " " + index);
Console.WriteLine(od.TryGetValue("b", out int value, out int idx) + $" {value} at {idx}");
False 1
True 2 at 1
Costs: lookup by key, lookup by index and appending are O(1). Insert, Remove and RemoveAt shift the entries after that position, so they're O(n). If you remove often from a large collection, that matters.
Don't confuse it with:
System.Collections.Specialized.OrderedDictionary, the old non-generic class from .NET Framework 2.0. It storesobjectkeys and values, which means boxing and casts. Use the generic one in new code.SortedDictionary<TKey,TValue>andSortedList<TKey,TValue>, which keep entries sorted by key, not by insertion order.
Alternate lookup: span keys without allocating strings
A common performance problem: you parse text, get a ReadOnlySpan<char> slice for a word or a header name, and need to look it up in a Dictionary<string, T>. Before .NET 9 you had to call ToString() on the slice, allocating a string just to do the lookup.
.NET 9 added alternate lookups. GetAlternateLookup<ReadOnlySpan<char>>() returns a view of the same dictionary that takes span keys:
string text = "the cat and the hat and the bat";
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var lookup = counts.GetAlternateLookup<ReadOnlySpan<char>>();
ReadOnlySpan<char> span = text;
foreach (Range r in span.Split(' '))
{
ReadOnlySpan<char> word = span[r]; // a slice: no string allocated
lookup[word] = lookup.TryGetValue(word, out int n) ? n + 1 : 1;
}
foreach (var (word, n) in counts.OrderByDescending(p => p.Value))
Console.WriteLine($"{word}: {n}");
the: 3
and: 2
cat: 1
hat: 1
bat: 1
MemoryExtensions.Split (.NET 9) yields Range values instead of new strings. Reads and updates of existing keys allocate nothing. A string is created only the first time a new key is added, because the dictionary has to store one.
To measure the difference, count words in 70,000 words of text with string.Split and with spans. GC.GetAllocatedBytesForCurrentThread() reports how many bytes the current thread has allocated so far:
string text = string.Join(' ', Enumerable.Repeat("the cat and the hat and the bat", 10_000));
// warm up both versions once so JIT allocations aren't counted
WithStrings(text); WithSpans(text);
long before = GC.GetAllocatedBytesForCurrentThread();
var a = WithStrings(text);
long mid = GC.GetAllocatedBytesForCurrentThread();
var b = WithSpans(text);
long after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"Split + string keys: {mid - before,10:N0} bytes, the={a["the"]}");
Console.WriteLine($"spans + alternate: {after - mid,10:N0} bytes, the={b["the"]}");
static Dictionary<string, int> WithStrings(string text)
{
var counts = new Dictionary<string, int>();
foreach (string word in text.Split(' '))
counts[word] = counts.GetValueOrDefault(word) + 1;
return counts;
}
static Dictionary<string, int> WithSpans(string text)
{
var counts = new Dictionary<string, int>();
var lookup = counts.GetAlternateLookup<ReadOnlySpan<char>>();
ReadOnlySpan<char> span = text;
foreach (Range r in span.Split(' '))
{
ReadOnlySpan<char> word = span[r];
lookup[word] = lookup.TryGetValue(word, out int n) ? n + 1 : 1;
}
return counts;
}
Split + string keys: 3,200,488 bytes, the=30000
spans + alternate: 624 bytes, the=30000
3.2 MB of short-lived strings and the array that holds them, compared with 624 bytes: the dictionary itself and its five keys.
Alternate lookups are available on Dictionary, HashSet, ConcurrentDictionary, FrozenDictionary and FrozenSet:
using System.Collections.Concurrent;
using System.Collections.Frozen;
// HashSet<string>
var stopWords = new HashSet<string> { "a", "an", "the" };
var stopLookup = stopWords.GetAlternateLookup<ReadOnlySpan<char>>();
Console.WriteLine(stopLookup.Contains("the quick".AsSpan(0, 3)));
// FrozenDictionary<string, T>
FrozenDictionary<string, int> ports = new Dictionary<string, int> { ["http"] = 80, ["https"] = 443 }
.ToFrozenDictionary();
var portLookup = ports.GetAlternateLookup<ReadOnlySpan<char>>();
ReadOnlySpan<char> url = "https://example.com";
Console.WriteLine(portLookup[url[..url.IndexOf(':')]]);
// ConcurrentDictionary<string, T>
var cache = new ConcurrentDictionary<string, int>();
var cacheLookup = cache.GetAlternateLookup<ReadOnlySpan<char>>();
cacheLookup.TryAdd("key".AsSpan(), 1); // the string is created only when the key is new
Console.WriteLine(cache["key"]);
// A comparer must implement IAlternateEqualityComparer<ReadOnlySpan<char>, string>
var custom = new Dictionary<string, int>(new LengthComparer());
Console.WriteLine(custom.TryGetAlternateLookup<ReadOnlySpan<char>>(out _));
try { custom.GetAlternateLookup<ReadOnlySpan<char>>(); }
catch (InvalidOperationException e) { Console.WriteLine(e.Message); }
class LengthComparer : IEqualityComparer<string>
{
public bool Equals(string? x, string? y) => x?.Length == y?.Length;
public int GetHashCode(string s) => s.Length;
}
True
443
1
False
The collection's comparer does not support the requested operation.
The lookup works only if the collection's comparer knows how to hash and compare the alternate key type the same way as the real key, which means it implements IAlternateEqualityComparer<TAlternate, TKey>. The default string comparer and the built-in StringComparer instances (Ordinal, OrdinalIgnoreCase and so on) do. A custom comparer doesn't unless you implement that interface yourself. Use TryGetAlternateLookup if you're not sure. Get the lookup once, outside the loop. It's a small struct that wraps the collection, so you can keep it in a local variable or a field.
Which one to use
- Items must come out by priority, not by arrival:
PriorityQueue<TElement,TPriority>. - A lookup table built once at startup and read on every request:
FrozenDictionary/FrozenSet, stored in astatic readonlyfield. - Searching text or bytes for any of a fixed set of characters or words:
SearchValues<T>, also in astatic readonlyfield. - A dictionary whose order matters, or that you need to access by position:
OrderedDictionary<TKey,TValue>. - Parsing text and looking up slices in a string-keyed collection:
GetAlternateLookup<ReadOnlySpan<char>>()on the collection you already have. - Everything else:
Dictionary<TKey,TValue>,HashSet<T>andList<T>are still the right default.