📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the Flyweight pattern? Explain intrinsic versus extrinsic state, how .NET uses flyweights (string interning, cached instances, SearchValues, frozen collections), when deduplicating objects actually saves memory, and how you would prove the saving with dotnet-gcdump.

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.

Senior Theory Advanced design-patterns flyweight gc memory performance string-interning

🎯 Key points

  • Flyweight shares many fine-grained objects by splitting state: intrinsic (shared, immutable, stored once) and extrinsic (context-specific, passed in by the client)
  • Shared flyweights must be immutable and thread-safe; a mutable flyweight changes every user at once
  • String literals are interned automatically; string.Intern adds strings to a process-wide pool that is never collected, so interning unbounded input leaks memory
  • A bounded or scoped pool (Dictionary/ConcurrentDictionary<string,string>, or .NET 9's Dictionary alternate lookup keyed by ReadOnlySpan<char>) deduplicates repeated values from files, JSON or databases without the leak
  • Cached instances are flyweights: Task.CompletedTask, cached Task<bool>, Array.Empty<T>(), Encoding.UTF8, CultureInfo.GetCultureInfo (read-only, cached)
  • SearchValues<T> and FrozenDictionary/FrozenSet (.NET 8+, current in .NET 10) trade a slower one-off build for faster lookups; build once at startup and share, never per call
  • It only pays off when many objects hold the same values (low cardinality, high count) in long-lived data; for unique values it adds lookup cost and memory
  • Prove it: dotnet-gcdump before and after (count and size of String or the type), plus dotnet-counters GC heap size and allocation rate, and a BenchmarkDotNet run for lookup cost

⏱ 30-second answer

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 literals are interned automatically. 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.
  • Cached instances are flyweights too: 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 cached Task<bool> results, Array.Empty<T>(), Encoding.UTF8 and CultureInfo.GetCultureInfo all hand out shared immutable instances instead of allocating. In .NET 8, SearchValues<T> and FrozenDictionary take 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 comparing dotnet-gcdump reports 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 vs extrinsic

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

Flyweights in .NET

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

When it pays off

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

Production example

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%.

🔍 What the interviewer is checking

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

  • Explains intrinsic vs extrinsic state and the immutability requirement.
  • Knows literal interning and why string.Intern on input leaks.
  • Names framework flyweights and the .NET 8 precomputed structures.
  • Measures with dotnet-gcdump and GC counters.

Red flags

  • Interns everything.
  • Shares mutable objects.
  • Claims savings without measurement.

📚 Learn in depth

1. Structure

Client ──▶ FlyweightFactory.Get(key) ──▶ pool: key → Flyweight (shared, immutable)
   │                                            ▲
   └── calls flyweight.Operation(extrinsicState)┘

The factory guarantees one instance per distinct intrinsic value.

2. How string interning works

  • The C# compiler emits string literals to the assembly's metadata. At run time the CLR interns them in a process-wide table, so identical literals across assemblies refer to one object.
  • string.Intern(s) returns the pooled instance for s's value, adding it if absent; string.IsInterned(s) checks without adding.
  • The intern table roots its strings, so they live for the life of the process (more precisely, until the runtime shuts down). Interning arbitrary input is therefore a leak, and string.Intern takes a lock internally.
  • Strings created at run time (from JSON, files, ToString(), concatenation) are not interned.

3. A controlled pool

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).

4. Precomputed shared structures

  • 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.

5. Enums and value types as flyweights

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.

6. Measuring

  1. 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.
  2. dotnet-counters monitor -p <pid> --counters System.Runtime: GC heap size, gen2 size, % time in GC.
  3. BenchmarkDotNet to confirm the pool lookup doesn't add unacceptable CPU on the load path.

Try it yourself

  1. Load 1 million rows with a repeated Colour column into objects; take a dotnet-gcdump; add a pool; compare.
  2. Show ReferenceEquals("abc", "abc") is true and ReferenceEquals("abc", new string("abc")) is false; then intern the second.
  3. Benchmark IndexOfAny(char[]) vs IndexOfAny(SearchValues<char>).
  4. Benchmark Dictionary vs FrozenDictionary lookups for 200 string keys.

💻 Code

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

⚠ Common mistakes

  • Mistake: Calling 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.
  • Mistake: Sharing mutable flyweights. Why it is wrong: Changing one changes it for every user, and concurrent writes are races. Instead: Flyweights must be immutable (records, readonly fields, frozen collections).
  • Mistake: Deduplicating high-cardinality values (order IDs, timestamps). Why it is wrong: Every lookup misses, so you pay for hashing and a dictionary entry per value with no saving. Instead: Apply it only to low-cardinality, high-count values.
  • Mistake: Using strings for small fixed sets (status, currency). Why it is wrong: Even deduplicated, they cost references and comparisons. Instead: Use enums or small value types.
  • Mistake: Creating 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.
  • Mistake: Claiming a memory win without measuring. Why it is wrong: The pool itself costs memory, and the win may be in gen0 data that didn't matter. Instead: Compare dotnet-gcdump snapshots and GC counters under the same load.
  • Mistake: Comparing strings by reference because "they're interned". Why it is wrong: Run-time strings usually aren't interned, so ReferenceEquals gives false negatives. Instead: Use string.Equals with an explicit StringComparison.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions SearchValues as a precomputed shared structure Why: Checks ReadOnlySpan and SearchValues in depth
    How to answer

    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.

  2. When: Candidate mentions frozen collections Why: Checks choosing between map types including FrozenDictionary
    How to answer

    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).

🛠 Real-world problems: how you handle them

In-memory catalogue used 1.9 GB because of millions of duplicate strings
Situation
A product search service on .NET [10] in Azure Container Apps that loaded [~4 million] attribute rows into memory at startup for fast filtering, with containers limited to [2 GB].
Signals
Containers were OOM-killed during the nightly reload; `dotnet-counters` showed the GC heap at [~1.9 GB] and gen2 pauses of [400+ ms]; p99 latency spiked during reloads.
Investigation
Took a `dotnet-gcdump` and found `System.String` was [~60%] of the heap, with [~11 million] instances. Sampling values showed only [~2,000] distinct attribute names and values such as 'Colour', 'Red', 'XL'. Each row deserialised fresh strings from the database.
Resolution
Immediate: raised the container memory limit temporarily. Real fix: a load-scoped string pool during materialisation, shared immutable `AttributeDefinition` objects, and `FrozenDictionary` indexes built once per reload and swapped atomically.
Prevention
A memory budget test in CI that loads a production-sized sample and fails above [800 MB]; dashboards for gen2 heap size and GC pause time; a guideline against `string.Intern` on external data.

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.

More in Structural Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me