Flyweight intent (share immutable intrinsic state, pass extrinsic state in), string literal interning and string.Intern's process-lifetime cost, custom string pools, cached instances (Task.CompletedTask, Array.Empty, CultureInfo), SearchValues and FrozenDictionary as precomputed shared state, and measuring with dotnet-gcdump and dotnet-counters.
Flyweight saves memory by sharing objects that would otherwise be duplicated thousands of times. It splits state into intrinsic state, which is shared, immutable and stored once, and extrinsic state, which is per use and passed in.
string.Intern puts strings in a pool that is never freed, so interning unbounded input leaks memory. Use a bounded or scoped pool for repeated values from files or JSON.Task.CompletedTask, Array.Empty<T>(), Encoding.UTF8, CultureInfo.GetCultureInfo.SearchValues<T> and frozen collections precompute a structure once and share it for every lookup.It only pays off for many objects with few distinct values, and shared objects must be immutable. Prove the saving with dotnet-gcdump before and after.
"Flyweight is a memory pattern: when you have a huge number of small objects that mostly carry the same values, you store each distinct value once and share it. The trick is splitting state. Intrinsic state is what's identical across many uses, like a product attribute name such as 'Colour', or the glyph data for a character. It's stored once in the flyweight and must be immutable, because everyone shares it. Extrinsic state is what differs per use, like the attribute's value for this product or the character's position on the page. The client keeps it and passes it in.
.NET uses the idea all over. String literals are interned, so every
"Pending"literal in your assembly is the same object.Task.CompletedTask, the cachedTask<bool>results,Array.Empty<T>(),Encoding.UTF8andCultureInfo.GetCultureInfoall hand out shared immutable instances instead of allocating. In .NET 8,SearchValues<T>andFrozenDictionarytake this further: you pay once to build an optimised structure, then share it across every lookup. For example, at [company] we loaded [~4 million] catalogue attribute rows into memory, with values like 'Colour', 'Size', 'Red' and 'XL' repeated millions of times as separate strings. I deduplicated them through a pool during loading and the heap went from [~1.9 GB] to [~650 MB], which I proved by comparingdotnet-gcdumpreports before and after.The mistake I see is reaching for
string.Intern. The intern pool lives for the life of the process and is never collected, so interning user input or unbounded data is a slow memory leak. I use a pool I control, scoped to the load or bounded in size. The other mistake is applying it to high-cardinality data, where the lookups cost more than they save. Flyweight is for many copies of few values, and you prove it with a heap snapshot, not a hunch."
| Intrinsic | Extrinsic | |
|---|---|---|
| Stored | Once, in the flyweight | By the client / context |
| Mutability | Immutable | Whatever the client needs |
| Example (catalogue) | Attribute name "Colour", value "Red" | Which product, display order |
| Example (text) | Glyph shape for 'A' | Position, colour on page |
| Flyweight | What is shared |
|---|---|
| Interned string literals | One string per distinct literal per process |
Task.CompletedTask, cached Task<bool> |
Completed task objects |
Array.Empty<T>() |
One empty array per T |
Encoding.UTF8, StringComparer.Ordinal |
Stateless singletons |
CultureInfo.GetCultureInfo("en-AU") |
Cached read-only culture |
SearchValues<char> (.NET 8) |
Precomputed vectorised search structure |
FrozenDictionary/FrozenSet (.NET 8) |
Read-optimised lookup built once |
| Pays off | Doesn't |
|---|---|
| Millions of objects, hundreds of distinct values | Mostly unique values (IDs, timestamps) |
| Long-lived data (caches, in-memory catalogues) | Short-lived request data that dies in gen0 |
| Values are immutable | Values are edited per use |
A pricing engine kept about 3 million rule objects in memory, each holding strings for region, channel and currency read from the database. There were only about 40 distinct regions, 6 channels and 3 currencies, but 9 million string instances. Deduplicating through a load-scoped pool and turning lookups into FrozenDictionary instances cut the gen2 heap by roughly 55% and full GC pause time by about 40%.
Checks memory-level understanding of .NET (interning, GC roots, immutability) and the judgement to apply sharing only where it matters, backed by measurement.
Green flags
string.Intern on input leaks.dotnet-gcdump and GC counters.Red flags
Client ──▶ FlyweightFactory.Get(key) ──▶ pool: key → Flyweight (shared, immutable)
│ ▲
└── calls flyweight.Operation(extrinsicState)┘
The factory guarantees one instance per distinct intrinsic value.
string.Intern(s) returns the pooled instance for s's value, adding it if absent; string.IsInterned(s) checks without adding.string.Intern takes a lock internally.ToString(), concatenation) are not interned.var pool = new Dictionary<string, string>(StringComparer.Ordinal);
string Dedup(string s) => pool.TryGetValue(s, out var existing) ? existing : (pool[s] = s);
Scope it to a bulk load and drop it afterwards; the strings themselves stay alive only as long as something references them. For span-based parsing, a pool keyed by ReadOnlySpan<char> avoids allocating a string just to look it up (the .NET 9 Dictionary.GetAlternateLookup<ReadOnlySpan<char>>() API enables exactly this).
SearchValues.Create("aeiou") analyses the set once and picks a vectorised algorithm; span.IndexOfAny(searchValues) reuses it. Store it in a static readonly field.FrozenDictionary spends extra time at creation analysing keys (length buckets, hashing strategy) to make every later lookup faster. It's ideal for configuration and reference data loaded at startup and shared.These are flyweights in spirit: the expensive intrinsic part is computed once and shared by every caller.
If a field has a small fixed set of values (status, currency), an enum or a small struct is better than a string: no object at all, no deduplication needed. Flyweight for strings is mainly for values you don't know at compile time.
dotnet-gcdump collect -p <pid> before and after, then compare in Visual Studio or with dotnet-gcdump report: look at System.String count and total size, and the size retained by your types.dotnet-counters monitor -p <pid> --counters System.Runtime: GC heap size, gen2 size, % time in GC.Colour column into objects; take a dotnet-gcdump; add a pool; compare.ReferenceEquals("abc", "abc") is true and ReferenceEquals("abc", new string("abc")) is false; then intern the second.IndexOfAny(char[]) vs IndexOfAny(SearchValues<char>).Dictionary vs FrozenDictionary lookups for 200 string keys.A load-scoped string pool, precomputed shared lookups, and an immutable flyweight:
namespace Catalogue;
using System.Buffers;
using System.Collections.Frozen;
// Intrinsic: shared, immutable attribute definition
public sealed record AttributeDefinition(string Name, string Unit);
// Extrinsic: per product, refers to the shared flyweights
public readonly record struct ProductAttribute(AttributeDefinition Definition, string Value);
public sealed class CatalogueLoader
{
// Pool scoped to one load: deduplicates repeated values without string.Intern's process-lifetime leak
private readonly Dictionary<string, string> _strings = new(StringComparer.Ordinal);
private readonly Dictionary<(string, string), AttributeDefinition> _definitions = new();
private string Dedup(string s) =>
_strings.TryGetValue(s, out string? existing) ? existing : _strings[s] = s;
private AttributeDefinition Definition(string name, string unit)
{
var key = (Dedup(name), Dedup(unit));
if (!_definitions.TryGetValue(key, out AttributeDefinition? def))
_definitions[key] = def = new AttributeDefinition(key.Item1, key.Item2);
return def; // one shared instance per distinct definition
}
public List<ProductAttribute> Load(IEnumerable<(string Name, string Unit, string Value)> rows) =>
rows.Select(r => new ProductAttribute(Definition(r.Name, r.Unit), Dedup(r.Value))).ToList();
}
public static class SharedLookups
{
// Precomputed once, shared by every request (thread-safe because read-only)
private static readonly SearchValues<char> InvalidSkuChars = SearchValues.Create(" /\\?#%&");
public static readonly FrozenDictionary<string, decimal> GstRateByCountry =
new Dictionary<string, decimal> { ["AU"] = 0.10m, ["NZ"] = 0.15m }
.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
public static bool IsValidSku(ReadOnlySpan<char> sku) =>
!sku.IsEmpty && sku.IndexOfAny(InvalidSkuChars) < 0;
}
// Measuring the effect
// dotnet-gcdump collect -p <pid> -o before.gcdump
// (deploy pooled loader)
// dotnet-gcdump collect -p <pid> -o after.gcdump
// dotnet-gcdump report before.gcdump | head -20 # compare System.String count and bytes
string.Intern on user input, file contents or JSON values. Why it is wrong: Interned strings are rooted for the life of the process; unbounded input becomes a memory leak. Instead: Use a pool you control, scoped to a load or bounded.SearchValues or a FrozenDictionary per call. Why it is wrong: Their construction is the expensive part; per-call creation is slower than the naive approach. Instead: Build once and store in static readonly or a singleton.dotnet-gcdump snapshots and GC counters under the same load.ReferenceEquals gives false negatives. Instead: Use string.Equals with an explicit StringComparison.Flyweight matters for long-lived, high-volume in-memory data: catalogues, rule sets, reference data and caches. For normal request-scoped objects the GC handles duplication cheaply, so I don't bother. The modern .NET twist is that the best "flyweights" are often precomputed structures (FrozenDictionary, SearchValues) shared from a singleton.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Do nothing | Short-lived or unique data | Duplicates die young | Large long-lived heaps |
| Scoped string pool | Bulk loads with repeated values | Dictionary during load | Unique values |
string.Intern |
Small, fixed, known set (rare) | Process-lifetime memory, lock | Any unbounded input |
| Enums / value types | Small fixed domains | Model change | Values unknown at compile time |
Frozen collections / SearchValues |
Read-only lookups shared by all requests | Build cost once | Data that changes often |
Evidence I'd show: dotnet-gcdump diffs (string count and bytes), gen2 heap size and full-GC pause time from dotnet-counters or Application Insights, before and after on the same dataset.
ReadOnlySpan<T> is the read-only version of Span<T>: same layout and ref struct rules, but the indexer returns ref readonly, so callers cannot modify the memory. Use it for inputs to parsing, searching and hashing, and Span<T> only for outputs you write to. It is the only span type that can view a string (text.AsSpan()) and constant data: static ReadOnlySpan<byte> Magic => [0x50, 0x4B, 0x03, 0x04]; points straight at data in the assembly with no allocation, and "GET "u8 gives UTF-8 bytes encoded at compile time. .NET 8's SearchValues<T> precomputes fast lookups for IndexOfAny. C# 14 makes span conversions first-class, so arrays and strings convert implicitly in more places, including extension method receivers and generic inference.
A map (associative array, dictionary) stores key → value pairs with unique keys. Choose the implementation by access pattern:
Dictionary<K,V>: hash table, O(1) average, unordered. The default.SortedDictionary<K,V>: red-black tree, O(log n), sorted by key, fast inserts/removes.SortedList<K,V>: two sorted arrays, O(log n) lookup but O(n) insert/remove; compact, indexable. Good for small or build-once sorted maps.OrderedDictionary<K,V> (.NET 9+): keeps insertion order with index access.ConcurrentDictionary<K,V>: thread-safe, lock-free reads.FrozenDictionary<K,V> (.NET 8+): built once, fastest reads.ImmutableDictionary<K,V>: immutable snapshots with cheap modified copies.ILookup<K,V> / Dictionary<K, List<V>>: multi-map (one key, many values).How to tell it (STAR)
**S:** At [company] our product search containers kept getting OOM-killed during the nightly catalogue reload. **T:** I had to cut memory use without slowing searches. **A:** A `dotnet-gcdump` showed strings were [60%] of the heap: [11 million] instances for only [about 2,000] distinct values. I added a pool scoped to the load so each distinct value was stored once, shared immutable attribute definitions, and built frozen lookup tables once per reload. I avoided `string.Intern` because it would never release the memory. **R:** The heap dropped from [~1.9 GB] to [~650 MB], gen2 pauses fell to [~80 ms], the OOM kills stopped, and a memory-budget test now guards it.
Last updated 18 Nov 2026.