HashSet vs Dictionary vs List in C#: Measured on .NET 10

Last updated: November 14, 2026 · Tested with .NET 10.0.12 (SDK 10.0.401) and .NET 11.0.0 (SDK 11.0.100), BenchmarkDotNet 0.15.8, Intel Core Ultra 5 125U, Windows 11

Short answer: for lookups, HashSet<T> and Dictionary<TKey,TValue> are the same speed. Pick by shape: a set of values or values by key. List<T>.Contains is the one that falls behind, and the element type decides when. With int, a list of 100 took 4.4–5.4 ns per lookup against 1.6–2.0 ns for the hash collections. At 1,000 items it was 33–35 ns, about 20 times slower. With string keys the list was already slower at 10 items (15.7–19.1 ns against 8.9–12.2 ns), and 13–19 times slower at 100. A HashSet<int> used 1,699 KB for 100,000 items, a Dictionary<int,bool> 2,123 KB, and a List<int> 391 KB.

This post used to be a Big-O cheat sheet with benchmark code but no results. This version runs the benchmarks on .NET 10 and .NET 11 GA and answers the “X vs Y” questions with the numbers I measured:

QuestionWhat I measured (.NET 10 / .NET 11)
List vs HashSet for Containsint: List is close up to ~100 items, 20x slower at 1,000, ~1,000x slower at 100,000. string: the list is behind from 10 items.
HashSet vs DictionarySame lookup speed (1.6–2.4 ns for int). HashSet uses 20% less memory: 1,699 KB vs 2,123 KB for 100,000 ints.
HashSet<T> vs Dictionary<T,bool>The bool saves nothing. Dictionary<int,bool> allocated exactly as much as Dictionary<int,int>.
List vs Dictionary for building100,000 items: List 155–214 µs, Dictionary 669–688 µs with a capacity, 2.1–2.2 ms without.
ToLookup vs Dictionary<K, List<V>>Hand-written dictionary loop built fastest (1.23–1.28 ms). ToLookup 1.43–1.48 ms. GroupBy + ToDictionary slowest, with 41% more allocation.
StringComparer.OrdinalIgnoreCase2.2–3.4x the cost of a default lookup. InvariantCultureIgnoreCase: 28–30x.

How I Tested It

One BenchmarkDotNet project, built twice: for net10.0 with SDK 10.0.401 and for net11.0 with SDK 11.0.100. BenchmarkDotNet 0.15.8 is the current stable release on NuGet. It doesn’t recognize net11.0 as a runtime moniker yet, so I used the in-process toolchain. Each build then measures the runtime it was built for. One side effect: the summary header says “.NET SDK 10.0.401” for both builds, because it reports the default dotnet on the machine. The Runtime line shows .NET 11.0.0 for the second build.

To keep the total time short I used a modest job instead of the default one:

var config = DefaultConfig.Instance
    .AddJob(Job.Default
        .WithToolchain(InProcessEmitToolchain.Instance)
        .WithWarmupCount(3)
        .WithIterationCount(10)
        .WithIterationTime(TimeInterval.FromMilliseconds(100)));

A full pass takes about three minutes per runtime. I ran two passes per runtime. The laptop throttles, and the first pass was up to 4 times slower than the second for some rows. The tables below use the second pass, which had much smaller error bars. Both passes are in the results folder. They agree on every ranking that I draw a conclusion from.

List vs HashSet vs Dictionary: Contains and Lookup

Each benchmark looks up 256 values that are all in the collection, picked at random. So List.Contains scans half the list on average. The time is per lookup:

[Params(10, 50, 100, 1_000, 100_000)]
public int N;

[Benchmark(Baseline = true, OperationsPerInvoke = Probes)]
public int List_Contains()
{
    int found = 0;
    foreach (int p in _probes) if (_list.Contains(p)) found++;
    return found;
}

[Benchmark(OperationsPerInvoke = Probes)]
public int HashSet_Contains()
{
    int found = 0;
    foreach (int p in _probes) if (_set.Contains(p)) found++;
    return found;
}

Here are the int results from .NET 10, as BenchmarkDotNet printed them:

| Method                 | N      | Mean         | Error      | StdDev     | Ratio | RatioSD | Allocated | Alloc Ratio |
| List_Contains          | 10     |     2.242 ns |  0.0599 ns |  0.0357 ns |  1.00 |    0.02 |         - |          NA |
| HashSet_Contains       | 10     |     1.739 ns |  0.0372 ns |  0.0246 ns |  0.78 |    0.02 |         - |          NA |
| Dictionary_TryGetValue | 10     |     1.702 ns |  0.0627 ns |  0.0373 ns |  0.76 |    0.02 |         - |          NA |
| List_Contains          | 100    |     4.416 ns |  0.1467 ns |  0.0873 ns |  1.00 |    0.03 |         - |          NA |
| HashSet_Contains       | 100    |     1.873 ns |  0.2905 ns |  0.1921 ns |  0.42 |    0.04 |         - |          NA |
| Dictionary_TryGetValue | 100    |     2.015 ns |  0.6627 ns |  0.4383 ns |  0.46 |    0.10 |         - |          NA |
| List_Contains          | 1000   |    35.270 ns |  1.6591 ns |  0.9873 ns |  1.00 |    0.04 |         - |          NA |
| HashSet_Contains       | 1000   |     1.901 ns |  0.4827 ns |  0.2524 ns |  0.05 |    0.01 |         - |          NA |
| List_Contains          | 100000 | 2,266.641 ns | 90.6617 ns | 53.9513 ns | 1.000 |    0.03 |         - |          NA |
| HashSet_Contains       | 100000 |     2.263 ns |  0.0589 ns |  0.0351 ns | 0.001 |    0.00 |         - |          NA |

The full picture, both runtimes, per lookup:

int, NList.ContainsHashSet.ContainsDictionary.TryGetValueFrozenSet.Contains
102.2 / 2.8 ns1.7 / 1.9 ns1.7 / 1.6 ns6.0 / 5.3 ns
503.3 / 3.3 ns1.7 / 1.8 ns1.8 / 1.6 ns2.4 / 2.3 ns
1004.4 / 5.4 ns1.9 / 1.7 ns2.0 / 1.6 ns2.4 / 2.5 ns
1,00035.3 / 33.2 ns1.9 / 1.7 ns1.7 / 1.6 ns2.4 / 2.3 ns
100,0002,267 / 2,233 ns2.3 / 2.2 ns2.4 / 2.1 ns2.9 / 2.8 ns

The surprise is how good List<int>.Contains is for small lists. Going from 10 to 100 items only doubled its time. For a primitive like int, List.Contains ends up in a vectorized span search (that is how the runtime implements it for primitives; I didn’t profile it), which compares several values per CPU instruction. Up to about 100 ints, the difference is under 4 ns per call. That only matters if you call it millions of times. By 1,000 items it’s 20 times slower, and at 100,000 it’s a thousand times slower. The hash collections stayed between 1.6 and 2.4 ns at every size.

The Gotcha: String Keys

Strings tell a different story. The probe strings are separate instances, as they would be when they come from a request or a file, so every comparison has to look at the characters. My keys share a prefix (customer-000123), which makes each comparison read most of the string:

| Method                 | N      | Mean           | Error         | StdDev        | Ratio | RatioSD | Allocated | Alloc Ratio |
| List_Contains          | 10     |      15.732 ns |     2.6741 ns |     1.7687 ns |  1.01 |    0.15 |         - |          NA |
| HashSet_Contains       | 10     |      11.830 ns |     0.2474 ns |     0.1636 ns |  0.76 |    0.08 |         - |          NA |
| Dictionary_TryGetValue | 10     |       8.916 ns |     0.2989 ns |     0.1779 ns |  0.57 |    0.06 |         - |          NA |
| FrozenSet_Contains     | 10     |       4.585 ns |     0.0649 ns |     0.0429 ns |  0.29 |    0.03 |         - |          NA |
| List_Contains          | 50     |      79.679 ns |     3.2596 ns |     2.1560 ns |  1.00 |    0.04 |         - |          NA |
| HashSet_Contains       | 50     |      12.301 ns |     0.2735 ns |     0.1809 ns |  0.15 |    0.00 |         - |          NA |
| List_Contains          | 1000   |   1,310.964 ns |    42.4839 ns |    28.1005 ns | 1.000 |    0.03 |         - |          NA |
| HashSet_Contains       | 1000   |      14.158 ns |     3.6987 ns |     2.4464 ns | 0.011 |    0.00 |         - |          NA |
| List_Contains          | 100000 | 188,647.201 ns | 5,353.3099 ns | 3,185.6689 ns | 1.000 |    0.02 |      10 B |        1.00 |
| HashSet_Contains       | 100000 |      18.565 ns |     3.8574 ns |     2.5514 ns | 0.000 |    0.00 |         - |        0.00 |
string, NList.ContainsHashSet.ContainsDictionary.TryGetValueFrozenSet.Contains
1015.7 / 19.1 ns11.8 / 10.6 ns8.9 / 12.2 ns4.6 / 5.6 ns
5079.7 / 96.5 ns12.3 / 8.3 ns8.2 / 10.5 ns8.5 / 8.7 ns
100143.5 / 163.4 ns10.8 / 9.3 ns8.4 / 8.5 ns8.2 / 8.4 ns
1,0001,311 / 1,511 ns14.2 / 10.2 ns10.2 / 9.9 ns11.2 / 10.5 ns
100,000188,647 / 223,659 ns18.6 / 14.0 ns13.2 / 13.7 ns13.1 / 15.1 ns

A string list can’t be vectorized. Each element is a separate string.Equals call, and the cost grows with N from the first item. At 10 strings the list was already the slowest of the four. At 50 it was 6–12 times slower. So the crossover you hear about (“List is fine for small N”) is real for int and much lower for string. If the keys are strings and you look things up in a loop, use a set or a dictionary from about 10 items.

In none of the four runs did List.Contains clearly beat HashSet.Contains, even at 10 items. The best it did was a tie inside the error bars. List<T> wins on other things, like building, memory and iteration order, not on lookups.

Build Cost and Memory

Filling each collection with 100,000 distinct ints, with and without a capacity up front. With a capacity, “Allocated” is the size of the finished collection:

100,000 intsTime (.NET 10 / .NET 11)Allocated
List.Add, no capacity470 / 440 µs1,025.5 KB
List.Add, capacity214 / 155 µs391 KB
HashSet.Add, no capacity1,695 / 1,698 µs4,721 KB
HashSet.Add, capacity631 / 508 µs1,699 KB
Dictionary.Add, no capacity2,201 / 2,057 µs5,900 KB
Dictionary.Add, capacity670 / 688 µs2,123 KB
Dictionary<int,bool>.TryAdd, capacity775 / 718 µs2,123 KB
ToFrozenSet()1,642 / 1,641 µs3,851 KB

Three things stand out:

  • Set the capacity. Without it, the HashSet allocated 2.8 times as much (all the arrays it outgrew) and took 2.7–3.3 times as long. A dictionary without capacity allocated 5,900 KB to end up holding 2,123 KB.
  • Hash collections cost memory. A presized HashSet<int> was about 17 bytes per item and a Dictionary<int,int> about 21.7. The list was 4 bytes per item. The same pattern held at 1,000 items: 3.96 KB for the list, 17.35 KB for the set, 21.67 KB for the dictionary.
  • Building a set costs about 3x a list (508–631 µs against 155–214 µs with capacities). If you only look up a handful of values, building the HashSet can cost more than the lookups it saves.

HashSet<T> vs Dictionary<T, bool>

Older code often uses Dictionary<T, bool> or Dictionary<T, byte> as a set. The value looks free, but it isn’t. Dictionary<int,bool> allocated 2,123 KB for 100,000 items, the same as Dictionary<int,int>. HashSet<int> needed 1,699 KB. A dictionary entry is a hash code, a next index, the key and the value. A one-byte bool gets padded to the same 16 bytes as an int. HashSet stores no value at all.

Lookups in HashSet<int> and Dictionary<int,int> were the same speed (1.6–2.4 ns at every size). I didn’t benchmark lookups in the bool version separately. Building a presized HashSet was faster than the presized Dictionary<int,bool> in all four measurements, by 6–41%. Beyond memory, the choice is about meaning. Use HashSet<T> when you only need “is it there?”, and use its Add return value to dedupe in one call. Use a dictionary when there’s a real value to store. HashSet<T> also gives you UnionWith, IntersectWith and SetEquals, which a dictionary doesn’t have.

ILookup (ToLookup) vs Dictionary<K, List<V>>

100,000 orders for 1,000 customers, grouped by customer. Then every customer’s orders are read once. The hand-written loop uses CollectionsMarshal.GetValueRefOrAddDefault, so each order costs one hash lookup:

var dict = new Dictionary<int, List<Order>>();
foreach (var o in _orders)
{
    ref var list = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, o.CustomerId, out _);
    (list ??= new List<Order>()).Add(o);
}
return dict;
| Method                     | Mean       | Error     | StdDev    | Ratio | RatioSD | Gen0     | Gen1     | Allocated | Alloc Ratio |
| Build_ToLookup             | 1,428.1 us |  90.78 us |  47.48 us |  1.00 |    0.04 | 343.7500 | 187.5000 | 2308838 B |       1.000 |
| Build_GroupBy_ToDictionary | 2,209.9 us | 460.74 us | 304.75 us |  1.55 |    0.21 | 500.0000 | 395.8333 | 3267078 B |       1.415 |
| Build_Dictionary_Loop      | 1,275.4 us |  73.90 us |  43.98 us |  0.89 |    0.04 | 364.5833 | 229.1667 | 2298416 B |       0.995 |
| Read_Lookup                |   532.5 us |   6.73 us |   3.52 us |  0.37 |    0.01 |        - |        - |   32034 B |       0.014 |
| Read_Dictionary            |   518.0 us |  16.98 us |  11.23 us |  0.36 |    0.01 |        - |        - |      28 B |       0.000 |

That’s .NET 10. On .NET 11 the order was the same: loop 1.23 ms, ToLookup 1.48 ms, GroupBy + ToDictionary 1.97 ms. ToLookup is only 10–20% slower than the hand-written loop and allocates the same. The common GroupBy(...).ToDictionary(g => g.Key, g => g.ToList()) is the one to avoid: it builds the groups and then copies every group into a new list. Reading was a tie. The lookup allocated 32 bytes per key read, because lookup[id] returns an IEnumerable and its enumerator is a heap object. A List<T> enumerator is a struct.

The bigger difference is behavior. I ran the same three orders through both:

[missing key: ILookup vs Dictionary]
lookup[99].Count() = 0, lookup.Contains(99) = False, lookup.Count = 2
dict[99]: KeyNotFoundException: The given key '99' was not present in the dictionary.

[duplicate keys: ToDictionary vs ToLookup]
ToDictionary: ArgumentException: An item with the same key has already been added. Key: 1
ToLookup: customer 1 has 2 orders

Use ToLookup when the data is built once and read many times, and a missing key should mean “no items”. It’s immutable, so nobody can add to it later. Use Dictionary<K, List<V>> when you keep adding items after the first build. For more grouping patterns, see my C# LINQ examples on .NET 10.

FrozenDictionary and FrozenSet

Since the queries ask about FrozenDictionary vs Dictionary: in these runs FrozenSet<T> was within about 1 ns of HashSet<T> for int from 50 items up, and slower at 10 items (5.3–6.0 ns). It was faster for 10 short strings (4.6–5.6 ns against 10.6–11.8 ns). Building it took 2.6–3.2 times as long as a presized HashSet (1.64 ms for 100,000 ints). On .NET 10 its allocation also changed between my two passes, 6,052 KB in one and 3,851 KB in the other. Frozen collections pay off for read-only data built once at startup. I measured them in depth, with string keys and lookup strategies, in C# Frozen Collections: High-Performance Guide, so I won’t repeat that here.

Pitfall 1: Case-Insensitive Keys and StringComparer

Same 1,000 keys, looked up in different ways. The ignore-case dictionaries get upper-case probes, so the comparer has to do the work:

_ordinalIgnoreCase = keys.ToDictionary(k => k, k => k.Length, StringComparer.OrdinalIgnoreCase);
_invariantIgnoreCase = keys.ToDictionary(k => k, k => k.Length, StringComparer.InvariantCultureIgnoreCase);
foreach (var p in _mixedCaseProbes) if (_lowered.TryGetValue(p.ToLowerInvariant(), out _)) found++;
| Method                               | Mean       | Error      | StdDev     | Ratio | RatioSD | Gen0   | Allocated | Alloc Ratio |
| Default_ExactCase                    |   9.184 ns |  0.1822 ns |  0.1084 ns |  1.00 |    0.02 |      - |         - |          NA |
| OrdinalIgnoreCase_MixedCase          |  20.364 ns |  2.7645 ns |  1.8285 ns |  2.22 |    0.19 |      - |         - |          NA |
| InvariantCultureIgnoreCase_MixedCase | 277.190 ns |  7.0762 ns |  4.2109 ns | 30.19 |    0.55 |      - |         - |          NA |
| ToLowerInvariant_ThenDefault         |  42.444 ns | 15.1841 ns | 10.0433 ns |  4.62 |    1.04 | 0.0089 |      56 B |          NA |

That’s .NET 11. On .NET 10 the second pass gave 9.9 ns, 33.7 ns, 278.1 ns and 39.0 ns. OrdinalIgnoreCase costs 2.2–3.4 times a plain lookup and allocates nothing. That’s the right choice for IDs, emails, header names and file extensions. The culture-aware comparer costs 28–30 times as much. I’ve seen it picked by accident through StringComparer.CurrentCultureIgnoreCase or an “invariant is safer” reflex. Calling ToLowerInvariant() on every key was in the same time range as OrdinalIgnoreCase, but it allocated 56 bytes per lookup. Microsoft’s best practices for comparing strings recommends ordinal comparison for exactly these non-linguistic keys.

Pitfall 2: A Mutable Key in a HashSet

A class with value equality based on a property that can change:

var customer = new Customer { Email = "ana@example.com" };
var seen = new HashSet<Customer> { customer };
customer.Email = "ana.silva@example.com";   // GetHashCode() now returns a different value

public override bool Equals(object? obj) => obj is Customer c && c.Email == Email;
public override int GetHashCode() => Email.GetHashCode();

The output was the same on .NET 10 and .NET 11:

[mutable key in a HashSet]
before: Contains = True, Count = 1
after changing Email: Contains = False, Count = 1
Any(c => c == customer) = True
Add(customer) again = True, Count = 2
Remove(customer) = True, Count = 1

The object is still in the set, but the set looks for it in the bucket of the new hash code. Contains says false, a second Add creates a duplicate of the same object, and Remove only removes the new copy. The original entry stays behind, and you can’t find it by key any more. No exception, no warning. The Object.GetHashCode docs say the hash code must not change while the object is used as a key. Use immutable keys: an ID, a string, or a record with init-only properties. I compare the equality you get from each type in records vs classes vs structs.

And a Bad GetHashCode

The opposite mistake: a key type whose GetHashCode() returns a constant. Every key lands in the same bucket, and each lookup becomes a list scan. I timed 20,000 adds plus 20,000 lookups with a Stopwatch:

.NET 10: run 2: good hash 1 ms, constant hash 1227 ms
.NET 11: run 2: good hash 1 ms, constant hash 1221 ms

Hundreds to a thousand times slower (the first, colder runs were 6–9 ms against 1,372–1,565 ms), and it still gives correct results, so tests don’t catch it. If you write GetHashCode by hand, use HashCode.Combine(...) over the same fields that Equals compares, or let a record generate it.

.NET 10 vs .NET 11

No difference I’d act on. Every ranking in this post is the same on both runtimes, and most numbers are within the run-to-run noise of this laptop. Allocations were identical apart from the FrozenSet variation above. The .NET 11 build ran a few rows faster in the second pass. Examples are List.Add with capacity (155 µs vs 214 µs) and OrdinalIgnoreCase (20.4 ns vs 33.7 ns). With only two passes on a throttling laptop, I wouldn’t call those a runtime improvement. If you’re upgrading, collection code needs no changes. My runtime async benchmarks cover a part of .NET 11 that did change performance.

Which Collection to Use

  • “Is X in here?” more than a few times: HashSet<T>. For int keys under ~100 items, a List is fine if you rarely call it. For string keys, switch from about 10 items.
  • Value by key: Dictionary<TKey,TValue> with TryGetValue. Same speed as a HashSet.
  • Don’t use Dictionary<T,bool> as a set. It’s 25% bigger than a HashSet and says less.
  • Many values per key, built once: ToLookup. Still adding later: Dictionary<K, List<V>> built with a loop, not GroupBy().ToDictionary().
  • Ordered data you iterate, or only search once: List<T>. It’s the cheapest to build and the smallest.
  • Read-only lookup data built at startup: consider FrozenSet/FrozenDictionary.
  • Always: pass a capacity when you know the count, use StringComparer.OrdinalIgnoreCase for case-insensitive keys, and never mutate a key.

The official guide to selecting a collection class covers the types I didn’t benchmark here, like Queue, Stack, SortedDictionary and the concurrent collections. If your hot path also slices strings or arrays, see my Span<T> tutorial.

What I Didn’t Test

  • Misses. Every probe was a hit. A miss makes List.Contains scan the whole list, so the list numbers above are its better case.
  • Other key types. Only int and one string shape (15-character keys with a shared prefix). Shorter strings, or strings that differ in the first character, compare faster in a list. Struct keys without IEquatable<T> box on every comparison. I didn’t measure either.
  • Iteration, Remove, Insert, SortedDictionary, Queue and concurrent collections.
  • Linux, ARM, server GC and other CPUs. Everything ran on one Intel Core Ultra 5 125U laptop on Windows 11. It throttles, so trust the rankings and the orders of magnitude more than the last digit.
  • The default BenchmarkDotNet job. I used 3 warm-up and 10 measured iterations of ~100 ms in-process, two passes per runtime. That’s enough for these gaps, which are 2x to 1,000x. It isn’t enough to measure a 5% difference.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *