Pattern 19/22 · Structural

Flyweight

Share the duplicated state across many objects instead of giving each object its own copy: the common part lives in one object reused by key, and the per-object part (external state) is passed in at the point of use.

Structural●●○12 min read8 stepsalso known as: Object cache, object pooling (different), shared metadata
structuralmemorygcgamecachecssinterning

01 — It starts with code that is breaking

Problem

Your game renders a forest. Someone writes class Tree { sprite, hitbox, leafColor, x, y }, creates 100,000 instances, opens a heap snapshot and sees tens of MB of sprite metadata repeated over and over. Filter by shape and all 100,000 objects fall into just 3 combinations of sprite/hitbox/leafColor — 99,997 objects are identical copies that differ only in x, y.

Text editor: every character in a 5MB file is an object holding { fontFamily, fontSize, color, bold, char }. Five million objects, while the number of distinct style combinations is 12 (body, heading, code, link...). You're paying RAM for the convenience of a constructor.

The web version of the same problem is far more familiar: you render a 5,000-row table and each row calls new Intl.NumberFormat(...) inside its format function, or each JSX item gets an inline style object created fresh on every render. A formatter is an expensive object (it caches locale data internally), and you're building 5,000 copies for the same locale. Inline style objects hurt in a different way: every parent render produces 5,000 new objects, and React has no way to skip the subtree.

The cost doesn't stop at RAM. It's allocation time, GC pauses when that pile of objects dies, and shared state you can't change centrally: changing the sprite for "oak" trees means hunting down 60,000 objects, or trusting that no object has "helpfully" modified the metadata for the whole species.

There's a quieter version too: you create a new Map(), a new RegExp(...), or a config object literal inside a function that gets called 200,000 times. The code looks innocent; the profiler sees a garbage printer.

02 — The idea, before touching code

Solution

Split the state in two. Intrinsic state: the part that depends only on "what kind of thing it is" (sprite, hitbox, format pattern, CSS rule) — it doesn't vary by context, can be shared, and ideally is frozen. External state: the part that depends on each individual (x, y, which character, which row, whose locale) — it lives outside the flyweight and is passed in at the point of use.

The rest of the "pattern" is just a Map: the flyweight factory. Calling kindOf("oak") 100,000 times returns the same object (genuinely ===). That's where all the power is: N entities but only K objects, and you control K.

Good news: you've been using flyweights all along, and the classless version is usually the better one. class="row row--paid" is a flyweight (one rule, 5,000 nodes); a module-scope Intl.NumberFormat used for the whole list is a flyweight; const ROW_STYLE = {...} outside the component instead of an inline object on every render is one too. Flyweight in JS is usually moving a declaration out of a loop, not building a system.

03 — Doing it for real, one code fragment per step

Step by step

1

Measure first: is this cost a number or a feeling?

Flyweight is an optimization, so it needs evidence. You need two numbers: how many objects you're building, and how many distinct value combinations there actually are. 200,000 objects / 2 combinations is a real problem. 200,000 objects / 180,000 combinations means you just wasted your time.

If the profiler doesn't point at this allocation (heap snapshot, performance.measure, flame graph), stop here. Don't write harder-to-read code to save something you haven't measured.

tsmeasure.ts
console.time('build')
const rows = Array.from({ length: 200_000 }, (_, i) => ({
  fmt: new Intl.NumberFormat('en-US'), // 200k formatters, each caching its own locale data
  id: i,
}))
console.timeEnd('build')

// Node: how much is the heap holding? Browser: DevTools > Memory > Heap snapshot.
console.log(Math.round(process.memoryUsage().heapUsed / 1024 / 1024) + ' MB')

// How many flyweights do you ACTUALLY need? Count the distinct combinations:
console.log(new Set(rows.map(() => 'en-US')).size) // 1 -> 200k objects for exactly one thing
The "objects : combinations" ratio is exactly how much a flyweight is worth. 200000 : 1 is very worth it. 3 : 2 is not.
Key pointWithout those two numbers (object count, combination count) this isn't Flyweight yet — it's just a taste for writing classes.
2

Split the state: what is "what kind", and what is "where"

List every field of the object and draw a line. Fields that only change when the species changes (the oak's sprite, the formatter's pattern) are intrinsic. Fields that change per individual or over time (x, health, timestamp) are external.

The tricky part of this step: a field that "looks shared" but actually varies per user (locale, tenant, theme) is not intrinsic — if you put it in the shared key, the key grows to match the number of users and the flyweight dissolves itself.

tssplit-state.ts
class Tree {
  // INTRINSIC: depends only on the tree KIND -> shareable, freezable
  sprite: string      // 'oak.png'
  hitbox: number      // 32
  leafColor: string   // '#2f6b2f'

  // EXTERNAL: depends on each tree -> NOT in the flyweight
  x: number
  y: number
  health: number      // changes every frame -> was intrinsic 5 minutes ago, not anymore
}
Rule of thumb: does this field change when just one specific tree changes? Yes -> external.
Key pointIntrinsic = "what kind of thing it is". External = "where it is, what state it's in". External comes in at the point of use, as parameters.
3

Build the flyweight factory: look up by key, freeze, never build twice

The factory is the whole machinery: a Map<key, Flyweight>; on a miss, create and Object.freeze; on a hit, return the existing object. Object.freeze isn't decoration — it's what protects you from the "some node modified the shared metadata and silently broke 60,000 other nodes" bug.

Keys should be short and enumerated by you (species name, style name). Don't serialize the whole object as a key: you'd just be trading RAM for RAM.

tstree-kind.ts
class TreeKind {
  static allocated = 0
  constructor(readonly sprite: string, readonly hitbox: number, readonly color: string) {
    TreeKind.allocated++
    Object.freeze(this) // shared means nobody gets to modify it
  }
}

const kinds = new Map<string, TreeKind>()

export function kindOf(name: 'oak' | 'pine'): TreeKind {
  let k = kinds.get(name)
  if (!k) {
    k = name === 'oak'
      ? new TreeKind('oak.png', 32, '#2f6b2f')
      : new TreeKind('pine.png', 16, '#1f4d3a')
    kinds.set(name, k)
  }
  return k
}
TreeKind.allocated is your sanity check: it should be roughly the number of SPECIES, not the number of TREES.
Key pointFlyweight factory = Map + freeze. Anything more than that and you're designing yourself extra problems.
4

External state comes in at the point of use, not inside the object

An entity is now just a thin row of data: key + external state, holding no metadata. Wherever metadata is needed, look up the flyweight right there. This is what decides whether you save 30MB or nothing at all.

Same flyweight, two calls, two results — no new object needed. That's the definition of "behavior comes from the state passed in".

tsrender.ts
// Drawing: metadata comes from the flyweight, position is passed in at the point of use.
// (draw() is a TreeKind method taking external state — see the demo below.)
for (const t of forest)
  kindOf(t.name).draw(t.x, t.y)

kindOf('oak').draw(0, 0)      // the same object
kindOf('oak').draw(999, 999)  // ...drawn in two different places
If your entity still holds sprite, this refactor hasn't saved a single byte.
Key pointAll the savings come from entities no longer holding metadata: keep one field and you keep N copies of that field.
5

The real web version: CSS classes are the browser's built-in flyweight

A CSS rule is parsed, resolved and cached once, then matched against countless elements. A class string is the cheapest key there is. Inline style is the broken flyweight: every element gets its own declaration, and every render a new object.

This is also the answer for JSX/Vue: :class="..." with a shared constant string beats :style="{...}" with an object literal created on every render, because a new object always diffs as different and kills any chance of skipping.

textrow.html
<!-- 5,000 nodes, ONE rule: the style metadata lives once -->
<li class="row row--paid">...</li>

<!-- 5,000 nodes, 5,000 declarations, rebuilt on every parent render -->
<li style="display:flex; padding:8px; color:#16a34a">...</li>

<!-- In a component: a string is safe, an object literal is a garbage printer -->
<li :class="ROW_CLASS">
<li :style="{ display: 'flex', padding: '8px' }">   <!-- new object / render / node -->
No class needed at all. You just used the browser's Flyweight — as long as you don't rewrite it yourself.
Key pointBefore writing a flyweight, check whether the browser/stdlib already shares it for you. It usually does.
6

Flyweights the engine and stdlib do for you

There are three expensive things people keep rebuilding inside loops: formatters (Intl.NumberFormat, Intl.DateTimeFormat, Intl.Collator), RegExp, and config objects. All three can be "built once, used for the whole list" right away, with a module-scope declaration or a Map keyed by parameter.

RegEx deserves its own mention: in modern JS, every time execution reaches a regex literal inside a function, you get a new object. Hoisting it out of the scope is a flyweight in the truest sense, and usually the quickest of the three fixes.

tsstdlib-flyweights.ts
// EXPENSIVE: one formatter per row, each caching its own locale data
const bad = (n: number) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(n)

// CHEAP: one instance for the whole list
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })
const good = (n: number) => usd.format(n)

// locale is external state, and there are few locales -> flyweight factory, like TreeKind
const formatters = new Map<string, Intl.NumberFormat>()
export function money(n: number, locale: string) {
  let f = formatters.get(locale)
  if (!f) formatters.set(locale, (f = new Intl.NumberFormat(locale)))
  return f.format(n)
}

// Regex: hoist to module scope, every run of a literal inside a fn is a new object
const NUMERIC = /^[0-9]+$/
These four lines usually win more than a whole hand-rolled flyweight framework.
Key pointFlyweight in JS is usually moving a declaration out of a loop, not building another registry.
7

String interning: the true part, and the part people get wrong

Plenty of articles use the first line of the code block below (which yields true) as proof that "the engine interns strings". The reasoning is wrong: the ECMAScript spec compares primitive strings by value, so the result is true whether or not the engine interns. Interning is an internal strategy, not the reason === works.

The genuinely interesting (and correct) part: new String("ab") === new String("ab") is false because those are two different objects — that's exactly where flyweight matters, and it also explains why === on objects compares references. Interning does exist in the engine, just somewhere === can't see: V8 internalizes property keys so every object shares one set of names, and objects with the same shape share one hidden class — meaning 1 million {x, y} objects cost just one shape. Flyweight, done by the engine, no API.

tsinterning.ts
'a' + 'b' === 'ab'                  // true  -> primitives compare by VALUE, not proof of interning
new String('ab') === new String('ab') // false -> two objects, two references

// Real interning happens at a level you can't measure with ===:
//  - property keys ('sprite', 'hitbox') are internalized -> one copy for the whole app
//  - objects with the same shape share a hidden class/shape -> 1M objects, 1 shape
// Practical takeaway: keep object SHAPES stable (same field order, no fields added
// at runtime) so the engine can share shapes for you.
Lesson: don't infer a language's behavior from an incidental side effect of the engine.
Key point=== on primitives compares values; interning is an engine internal. Tell this story correctly and nobody can catch you out.
8

Verify it — and know when to stop

Before claiming "it's flyweighted", three assertions: is the flyweight really the same object, is it frozen, and is the allocation counter roughly the number of kinds? Without these three, it's very easy to write a factory that still builds a new object every time.

And the stopping condition, bluntly: if the key space is unbounded (keys derived from user ids, from input data), or if your flyweight holds a single number, then don't. A Map lookup + string key isn't necessarily cheaper than a small object that V8 allocates with a pointer bump and cleans up with the scavenger at near-zero cost.

tsverify.ts
console.log(kindOf('oak') === kindOf('oak'))  // true  -> genuinely shared
console.log(Object.isFrozen(kindOf('oak')))   // true  -> nobody can modify it
console.log(TreeKind.allocated)               // 2     -> not 100000

// Signs you should stop / revert:
//  - key comes from user data  -> the Map grows to match the number of users
//  - flyweight holds 1 number  -> the lookup costs more than storing it directly
//  - profiler shows no drop    -> you just added indirection for free
Flyweight only pays off when K (number of flyweights) is much smaller than N (number of entities), and you can prove it with numbers.
Key pointProve K << N with logs or a heap snapshot and your flyweight is working; otherwise it merely exists.

04 — Who talks to whom

Structure

  • FlyweightThe intrinsic part: metadata for one KIND (`TreeKind`: sprite, hitbox, color). No per-instance state, so it can be `Object.freeze`d.
  • FlyweightFactory`Map<key, Flyweight>`: look up the key, create + freeze on a miss, return **the same object** on a hit. The only place allowed to `new`.
  • ExternalStateThe per-entity part: `x`, `y`, `health`, locale. Passed in at the point of use, never stored in the flyweight.
  • ClientHolds N thin data rows `{ name, x, y }` and calls `kindOf(name).draw(x, y)`. RAM cost scales with K, not N.
   Client: 100,000 entities, each just a key + external state

     forest[0] = { name: 'oak',  x: 0,  y: 0 }
     forest[1] = { name: 'pine', x: 1,  y: 0 }
     forest[2] = { name: 'oak',  x: 2,  y: 0 }        intrinsic state (frozen)
     ...                                              ┌──────────────────────┐
              kindOf(name)                            │ TreeKind 'oak'       │
        ┌───────────────────► Map {                   ├──────────────────────┤
        │                       'oak'  -> #1 ─────────┤ TreeKind 'pine'      │
        └───────────────────  'pine'  -> #2           └──────────────────────┘
                              }
     100,000 lookups · 2 objects · kindOf('oak') === kindOf('oak') -> true

05 — Edit freely, run it right here

Try it: 100,000 trees, 2 objects actually built

tsdemo.ts
// --- Intrinsic state: the SHARED part, built once per kind ---
class TreeKind {
  static allocated = 0

  constructor(
    readonly sprite: string,
    readonly hitbox: number,
    readonly color: string,
  ) {
    TreeKind.allocated++
    Object.freeze(this)
  }

  // x, y are EXTERNAL state: passed in at the point of use, not stored in the flyweight
  draw(x: number, y: number) {
    console.log(this.sprite + ' @' + x + ',' + y + ' hit=' + this.hitbox)
  }
}

// --- Flyweight factory: look up by key, always return the SAME object ---
const kinds = new Map<string, TreeKind>()
function kindOf(name: 'oak' | 'pine'): TreeKind {
  let k = kinds.get(name)
  if (!k) {
    k = name === 'oak'
      ? new TreeKind('oak.png', 32, '#2f6b2f')
      : new TreeKind('pine.png', 16, '#1f4d3a')
    kinds.set(name, k)
  }
  return k
}

// --- 100k "trees": each tree is just a thin row of data ---
const forest: { name: 'oak' | 'pine', x: number, y: number }[] = []
for (let i = 0; i < 100_000; i++)
  forest.push({ name: i % 3 === 0 ? 'pine' : 'oak', x: i % 40, y: Math.floor(i / 40) })

for (const t of forest.slice(0, 4))
  kindOf(t.name).draw(t.x, t.y)

console.log('trees=' + forest.length + ' TreeKind actually built=' + TreeKind.allocated)
console.log('same object=' + (kindOf('oak') === kindOf('oak')) + ' frozen=' + Object.isFrozen(kindOf('oak')))
console
pine.png @0,0 hit=16
oak.png @1,0 hit=32
oak.png @2,0 hit=32
pine.png @3,0 hit=16
trees=100000 TreeKind actually built=2
same object=true frozen=true

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • Large numbers of entities differ only in a few contextual fields (position, order, id), and the rest repeats across a small number of groups.
  • You have measured: a heap snapshot or profiler points squarely at this allocation as the cost, not a guess.
  • You control how the data arrives (sprite atlas, binary buffer, scene graph, document model), so entities can hold just a key.
  • Expensive objects with few parameters: Intl.NumberFormat, Intl.Collator, DateTimeFormat, regexes, font faces, WebGL buffers — same parameters means reusable.
  • You need to cap the number of instances for resource reasons (GPU buffers, loaded fonts, connections), not just RAM.
  • The platform already has a sharing layer (CSS rules, hidden classes, texture cache) and your job is not to break it with a new object on every render.

Don't use it when

  • Optimizing without measuring. Flyweight trades readability + one layer of indirection. If the number of combinations is close to the number of objects, all you get is a useless Map and harder-to-read code.
  • Shared = mutations spread. One place writing kind.hitbox = 64 reshapes 60,000 nodes, and the bug lives in another file. Object.freeze + readonly types, and every field that can change over time has to move out.
  • An unbounded key is a fake flyweight. Keys derived from user ids, tenant ids, or user-entered format strings → the Map grows to match the number of data rows, plus the cost of hashing and lookups.
  • Harder debugging. A heap snapshot shows one object referenced from 100,000 places; a breakpoint asking "which node does this object belong to" stops making sense. External state has to be enough to reconstruct context (log key + coordinates + frame).
  • In JS, the engine already does the hard part. Small-object allocation is very cheap, young-gen GC is nearly free, property keys are already internalized, shapes are shared, styles are grouped by CSS rule. Hand-written flyweights win on big metadata and expensive instances, and lose on 3-field objects.
  • Turning it into a system. An LRU cache, an eviction policy, a registry chain for a 5,000-row table: that's over-engineering with a name. A module-scope const solves 80% of cases.

07 — You have met it already, just not by name

In real code

CSS classes in the browser

A rule like display:flex; color:#16a34a is parsed and resolved once, then applied to countless elements; the class string is the key. Inline style is the unshared version, and it's slower for exactly the reasons the flyweight mechanism describes.

V8: internalized strings and hidden classes

The engine internalizes property keys so every object shares one set of names, and objects with the same shape share one hidden class (shape). 1 million { x, y } objects cost just one shape — the flyweight lives in the compiler, and keeping object shapes stable is how you benefit from it.

Intl.NumberFormat / Intl.Collator

Each instance holds loaded and cached locale data. Both the docs and common practice recommend creating one instance and reusing it for many values; for multiple locales, a Map keyed by locale — in other words, a flyweight factory.

JS game engines: texture cache and instancing

PixiJS caches textures by key so thousands of sprites point at the same BaseTexture; Three.js has InstancedMesh (one geometry + N matrices), pushing the sharing down to the GPU. Same idea: N entities, K resources.

08 — Try it yourself

Exercise

A 5,000-row table renders like this: `renderRow(item, locale)` contains `new Intl.NumberFormat(locale, ...)`, `/^[0-9]+$/.test(item.sku)`, and the JSX sets `style={{ display: "flex", padding: 8 }}`. Identify the three things that can be shared, fix them, and say exactly where the fix is faster/cheaper: RAM, CPU, or GC?

Hints, open them one at a time:

  1. For each one: does it depend on "what kind" (locale, pattern) or on "which row"? Whatever depends on the kind is intrinsic.
  2. Is the set of locales small? If so, Map<locale, formatter> is a flyweight factory; if not, you're caching in the wrong place.
  3. The style object literal in JSX: who creates it, how many times, and who has to clean it up?

The formatter + regex are intrinsic (few combinations) → module scope, or a Map keyed by locale. The style object → replace with a constant class string. Result: 5,000 formatters + 5,000 regexes + 5,000 style objects become 1 formatter per locale + 1 regex + 1 class. Cheaper on all three: RAM (fewer instances), CPU (less parsing/initialization), and GC (less young garbage on every parent render).

tsexercise.ts
// Module scope: built ONCE for the lifetime of the page
const NUMERIC = /^[0-9]+$/
const ROW_CLASS = 'row row--flex'

// intrinsic per locale (small set of locales), external is the value being formatted
const formatters = new Map<string, Intl.NumberFormat>()
function nf(locale: string) {
  let f = formatters.get(locale)
  if (!f) formatters.set(locale, (f = new Intl.NumberFormat(locale, { style: 'currency', currency: 'USD' })))
  return f
}

export function renderRow(item: { sku: string, amount: number }, locale: string) {
  return {
    class: ROW_CLASS,                       // shared, no new object on every render
    numeric: NUMERIC.test(item.sku),
    amount: nf(locale).format(item.amount),
  }
}

09 — Read them in pairs to see the essence

Related patterns

  • PrototypeBoth answer "how do I get many similar objects", but from opposite directions: Prototype **creates new objects** by copying, Flyweight tries **not to create** new objects. Prototype spends RAM to isolate, Flyweight saves RAM by sharing.
  • CompositeA classic pair in scene graphs: Composite gives you the tree (100,000 nodes), Flyweight gives you the metadata shared between nodes. Composite describes the shape, Flyweight describes the cost.
  • SingletonA flyweight factory and a singleton share the "one single instance" idea. The difference: singleton is a statement about count, flyweight is a strategy of shared state + external state. Your factory lives like a singleton, but that's not what the pattern is about.
  • FacadeFacade bundles many APIs into one to make them easy to use; flyweight bundles many copies of **data** into one to make them cheap. Both are "don't let every client hold its own copy".