AlgoViz

Flyweight

medium 50 min

The Flyweight pattern shares what is the same in very many objects.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:45

Flyweight

1:03Reel

Theory

Read or listen first. About 2 min.

What it is

Flyweight is a structural design pattern that saves memory by sharing. Objects that would be equal in large parts refer to one shared object for that part.

The shared part is called intrinsic state: it does not depend on where the object is used, and it never changes. The rest is extrinsic state: it depends on the place and is passed in when an operation is called.

A factory hands out the shared objects. It keeps a map from key to flyweight, so that for each key only one exists.

Why it exists

Programs often hold thousands or millions of small things that are nearly alike: letters in a text, trees in a game, cells in a table, rows with the same city name.

Storing the equal part in each of them fills memory with copies. It also costs time to load and to fill the processor cache with the same bytes again and again.

With the pattern, heavy memory grows with the number of kinds. A forest of 10,000 trees of three kinds needs three meshes.

The price is that the shared object knows nothing about its place. Callers must bring it, and two places can no longer be told apart by the object.

A short history

  1. 1990

    Paul Calder and Mark Linton publish Glyphs: Flyweight Objects for User Interfaces. Each character in a document becomes a shared object.

  2. 1994

    The book Design Patterns lists Flyweight among its structural patterns, with a document editor as its example.

  3. 2004

    Java 5 introduces boxing. The language rule that equal small values, such as -128 to 127, box to the same object is a flyweight by specification.

  4. 2009

    Boost 1.38, released on 8 February, contains Boost.Flyweight, a C++ library for large quantities of highly redundant objects.

  5. 2025

    JEP 519 makes compact object headers a product feature of JDK 25. Switched on, they make every small object cheaper.

Words to know

Flyweight
A shared, immutable object that stands for the equal part of many.
Intrinsic state
What is the same in every place. Stored in the flyweight.
Extrinsic state
What depends on the place. Kept outside and passed in.
Context
The small object per use: extrinsic state and a reference.
Flyweight factory
The only place that creates flyweights. One per key.
Key
The values that decide which flyweight it is: exactly the intrinsic state, or its name.
Unshared flyweight
Same interface, own state, not in the factory.
Interning
Replacing equal values by one shared object, for example strings.
Glyph
The shape of one character in one font and size.
Weak reference
A reference that does not keep its object alive.
Instancing
Drawing one mesh at many places with one call.
Dictionary encoding
Storing small numbers and one list of the values they stand for.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Ask for a kind. The factory returns the one shared object

Understand it

Start here

Few stamps, many trees

Draw a forest of thirty trees by hand and you draw thirty trees. Carve a rubber stamp and you carve one. The stamp does not know where it will be pressed, and it does not need to. The Flyweight pattern does this with objects: what is the same everywhere is stored once, what differs stays small and outside.

Asha prints a forest
2 of 30

One star stamp or a hundred glitter stickers: the hundred stickers need a hundred times the glitter.

Five parts

  • Flyweight

    The interface. Its operations take the extrinsic state as parameters: draw(x, y, tint).

  • Concrete flyweight

    Holds the intrinsic state: mesh, texture, glyph. Never changes after construction.

  • Factory

    A map from key to flyweight. Returns the one that exists or makes it. Clients never call the constructor.

  • Context

    The small object, one per use: position, colour, and a reference to its flyweight.

  • Unshared flyweight (optional)

    Implements the same interface and is not shared, for example a row that holds flyweights as children.

Why

Seven gigabytes of the same three pictures

A game draws a forest of 10,000 trees. There are three kinds: oak, pine and birch. A tree needs a mesh of 500 KB, a texture of 200 KB and a position. The first version of the class holds all of it.

Python
class Tree:    def __init__(self, x, y, kind):        self.mesh = load_mesh(kind + ".obj")          # 500 KB, every time        self.texture = load_texture(kind + ".png")    # 200 KB, every time        self.x, self.y = x, yforest = [Tree(rand(), rand(), "oak") for _ in range(10_000)]    # out of memory
Every tree loads its own files. 10,000 loads and 10,000 copies.

The bill

10,000×700 KB=7 GB3×700 KB+10,000×24 B=2.1 MB+0.24 MB=2.34 MB10{,}000 \times 700\,\text{KB} = 7\,\text{GB} \qquad 3 \times 700\,\text{KB} + 10{,}000 \times 24\,\text{B} = 2.1\,\text{MB} + 0.24\,\text{MB} = 2.34\,\text{MB}
99.97 percent less. The 24 bytes are one small object with two ints and a reference. The FAANG interview page on memory counts them one by one.

The design that hurts

10,000Forest- trees: List<Tree>+ draw(canvas)Tree- mesh: 500 KB- texture: 200 KB- x, y: int+ draw(canvas)

1/2A complete tree

Nothing is wrong with one such object. It is simple and stands alone.

owns (dies together)uses

The class mixes two kinds of facts: facts about oaks, and facts about this oak.

The idea

Split the state

IntrinsicExtrinsic
QuestionIs it the same in every place?Does it depend on the place?
StoredOnce, in the flyweightIn the context, or worked out when needed
ChangesNeverFreely
Reaches the operationIt is already thereAs a parameter
TreeMesh, texture, namePosition, tint, age
Letter in a textShape, font, size, widthPosition, line, selected or not
Chess pieceMoves, picture, colourSquare, has it moved
BulletSprite, damage, speedPosition, direction, who fired it
The whole pattern is this table. The rest is bookkeeping.

Where does a field go?

The last question is honest: two bytes that are the same everywhere are not worth a class.

The Flyweight pattern in general

«interface»Flyweight+ operation(extrinsic)

1/5The interface

An operation that takes everything it needs to know about the place as parameters.

owns (dies together)implementshas (lives on)

Often the interface is left out, because there is only one kind of flyweight.

Plant two oaks

Two trees, one load, one TreeType. The last two calls differ only in what is passed in.
Python
loads = []class TreeType:    def __init__(self, name):        loads.append(name)              # stands for reading 700 KB        self.name = name    def draw(self, x, y):        return f"{self.name} at {x},{y}"cache = {}def tree_type(name):    if name not in cache:        cache[name] = TreeType(name)    return cache[name]names = ["oak", "pine", "birch"]forest = [(i % 100, i // 100, tree_type(names[i % 3])) for i in range(10_000)]print(len(forest), "trees,", len(loads), "loads,", len({id(t) for _, _, t in forest}), "tree types")x, y, t = forest[4]print(t.draw(x, y))
The pattern in twenty lines. Run it: 10,000 trees, three loads.
Edit and run it in your browser

The trap

The key decides how much you share

Trees come in three colours. If the colour becomes part of the flyweight, the key is kind and colour, and there are 3 x 3 = 9 flyweights. If each of them loads its own mesh, that is 6.3 MB instead of 2.1 MB. If the colour is passed in when drawing, there are still three.

Where does the colour of a tree go?

BreaksIn the flyweight, with a setter
How
oak.color = "orange" before each draw.
Limit
All oaks share it. The next one who forgets to set it paints in the last colour, and two threads paint each other's trees.
Choose when
Never.
WorksIn the key
How
get("oak", "orange"): nine flyweights.
Limit
Kinds times colours. With free colours there is one flyweight per tree, and nothing is shared.
Choose when
Few values, and the texture really differs per colour.
StrongOutside, passed to draw
How
Each tree keeps one byte of tint. type.draw(x, y, tint).
Limit
The context grows by a field.
Choose when
The picture is the same and only tinted.

The number of flyweights is the number of keys

KeyFlyweights for 10,000 treesShared well?
kind3Yes
kind, colour9Yes
kind, colour, age in years up to 80720Hardly
kind, exact heightup to 10,000No: one per tree, plus a cache
If the number of keys grows with the number of objects, you built a slower version of the first design.

Second example

Letters in a text

This is where the pattern comes from. A text of 100,000 characters uses perhaps 100 combinations of letter, font and size. A letter object with its outline, font and metrics may take 1 KB.

Hello needs four glyphs

Five places, four glyphs. The word keeps the order, so not even the positions are stored.
One object per letterFlyweight
Hello5 x 1 KB = 5 KB4 x 1 KB = 4 KB and 5 references
100,000 letters100,000 x 1 KB = 100 MB100 x 1 KB + 100,000 x 8 B = 0.1 MB + 0.8 MB = 0.9 MB
For Hello the pattern is silly. For the document it saves about 99.1 percent, and what is left are the references.

Choosing

When to use it and when not

Use it when

  • There are very many objects: thousands or more
  • Most of their bytes are the same for a few kinds
  • The shared part can be immutable
  • Memory is the measured problem: games, phones, caches, big documents
  • Nobody relies on which of two equal objects they hold

Leave it when

  • There are few objects
  • Most of them are different
  • The shared part is small
  • The shared part changes per object
  • The extra parameters make the code hard to read for little gain

Is it worth it?

The first question is the one that is skipped.

The price

  • More parameters

    The flyweight can not answer where it is. Everyone who calls it must know.

  • Time for memory

    Extrinsic state is looked up or calculated at each call.

  • Identity is gone

    Two letters l are the same object. Selecting this l needs its place, not the object.

  • A cache to look after

    The factory needs a policy for threads and for things that nobody uses any more.

Summary

The whole topic in one minute.

Split the state: what is true for all oaks goes into one immutable TreeType, what is true for this oak stays in a small Tree and is passed to draw. A factory makes sure that there is one type per key.

The key must be exactly the intrinsic state. Too fine a key shares nothing, too coarse a key mixes things up. Test identity and the number of loads, because a factory that shares nothing still draws the right picture.

In production: build once per key under load, decide who keeps flyweights alive, store millions of contexts as columns, never compare or lock shared objects by accident, and take the pattern out when the heap snapshot does not show it.

  • Intrinsic: same everywhere, stored once, never changes. Extrinsic: depends on the place, passed in.
  • Clients get flyweights from the factory only. The key is exactly the intrinsic state.
  • Memory grows with the number of kinds plus a little per object.
  • A mutable flyweight is a bug that shows in places you did not touch.
  • If nearly every object has its own key, you share nothing.
  • Measure first: few objects or small parts are not worth it.

Sources