Flyweight
medium 50 minThe Flyweight pattern shares what is the same in very many objects.
Video lesson · Chapter 1 of 6
Make a prediction
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
1990
Paul Calder and Mark Linton publish Glyphs: Flyweight Objects for User Interfaces. Each character in a document becomes a shared object.
1994
The book Design Patterns lists Flyweight among its structural patterns, with a document editor as its example.
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.
2009
Boost 1.38, released on 8 February, contains Boost.Flyweight, a C++ library for large quantities of highly redundant objects.
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.
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.
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.
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 memoryThe bill
The design that hurts
1/2A complete tree
Nothing is wrong with one such object. It is simple and stands alone.
owns (dies together)uses
The idea
Split the state
| Intrinsic | Extrinsic | |
|---|---|---|
| Question | Is it the same in every place? | Does it depend on the place? |
| Stored | Once, in the flyweight | In the context, or worked out when needed |
| Changes | Never | Freely |
| Reaches the operation | It is already there | As a parameter |
| Tree | Mesh, texture, name | Position, tint, age |
| Letter in a text | Shape, font, size, width | Position, line, selected or not |
| Chess piece | Moves, picture, colour | Square, has it moved |
| Bullet | Sprite, damage, speed | Position, direction, who fired it |
Where does a field go?
The Flyweight pattern in general
1/5The interface
An operation that takes everything it needs to know about the place as parameters.
owns (dies together)implementshas (lives on)
Plant two oaks
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 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
| Key | Flyweights for 10,000 trees | Shared well? |
|---|---|---|
| kind | 3 | Yes |
| kind, colour | 9 | Yes |
| kind, colour, age in years up to 80 | 720 | Hardly |
| kind, exact height | up to 10,000 | No: one per tree, plus a cache |
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
| One object per letter | Flyweight | |
|---|---|---|
| Hello | 5 x 1 KB = 5 KB | 4 x 1 KB = 4 KB and 5 references |
| 100,000 letters | 100,000 x 1 KB = 100 MB | 100 x 1 KB + 100,000 x 8 B = 0.1 MB + 0.8 MB = 0.9 MB |
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 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
- Calder and Linton: Glyphs, flyweight objects for user interfaces (record)
- Java SE 21: String.intern
- Java SE 21: Integer.valueOf
- JEP 519: Compact Object Headers
- JEP 390: Warnings for Value-Based Classes
- Python C API: integer objects
- Python: weakref
- Swing: DefaultTableCellRenderer
- Unity: GPU instancing
- Boost.Flyweight
- Guava: Interners
- Design Patterns (publisher's page)