On this page

Flyweight

Flyweight is a memory optimisation dressed as a design pattern. When a program creates a very large number of objects that are mostly the same, it splits each object's state in two: the part that's identical across many objects (shared, stored once) and the part that's unique to each one (kept small, or passed in from outside). A factory makes sure that each distinct piece of shared state exists exactly once.

The structural patterns overview covers Adapter, Bridge, Composite, Decorator, Facade and Proxy, and doesn't include a Flyweight section, so this page starts from the beginning. It covers intrinsic versus extrinsic state, a thread-safe flyweight factory, an implementation in three languages with actual memory measurements, the flyweights already built into Java and Python (string interning, boxed integer caches), and the most important rule for this pattern: measure before you use it, and measure after.

Intent

Use sharing to support large numbers of fine-grained objects efficiently, by storing the state they have in common once and supplying the state that differs from outside.

Two terms carry the whole pattern:

  • Intrinsic state is the part of an object that doesn't depend on its context and is the same for many objects. For a particle in a game: its sprite image, its colour palette, its physics constants. For a character in a text editor: the glyph outline for "e" in a given font and size. Intrinsic state lives inside the flyweight, is shared, and must be immutable.
  • Extrinsic state is the part that depends on context and differs per object. For the particle: its position and velocity. For the character: where on the page it sits. Extrinsic state lives outside the flyweight, either in a small per-object record or in arrays owned by the client, and is passed in to the flyweight's methods when needed.

If you can't draw that line cleanly, or if the shared part is small, Flyweight won't help you.

The problem

You're writing the particle system for a 2D game. Explosions, sparks and smoke puffs each spawn hundreds of particles, and a busy scene has tens of thousands alive at once. The first version gives every particle everything it needs to draw itself, including its own copy of the sprite bitmap.

import random
import tracemalloc

SPRITE_BYTES = 2048          # a small 32x16 RGBA bitmap
COLORS = {"spark": "#ffd34d", "smoke": "#888888", "ember": "#ff5a1f"}


def load_sprite(kind: str) -> bytes:
    """Pretend to decode a PNG from disk. Returns a NEW bytes object every call."""
    return bytes([sum(map(ord, kind)) % 256]) * SPRITE_BYTES


class Particle:
    __slots__ = ("kind", "sprite", "color", "x", "y", "vx", "vy")

    def __init__(self, kind: str, x: float, y: float, vx: float, vy: float) -> None:
        self.kind = kind
        self.sprite = load_sprite(kind)      # 2 KB per particle, identical for every spark
        self.color = COLORS[kind]
        self.x, self.y, self.vx, self.vy = x, y, vx, vy


rng = random.Random(7)
tracemalloc.start()
particles = [Particle(rng.choice(list(COLORS)), rng.random() * 800, rng.random() * 600,
                      rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(20_000)]
used, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()

assert len({id(p.sprite) for p in particles}) == 20_000      # 20,000 copies of 3 images
assert used > 20_000 * SPRITE_BYTES                          # at least 40 MB of sprites
print(f"before: {used / 1e6:.1f} MB for 20,000 particles")

There are three kinds of particle, so there are three distinct sprites. The program stores twenty thousand. Most of the memory is spent on copies of the same three bitmaps:

  1. Memory grows with the particle count times the size of the shared data. At 2 KB per sprite, 20,000 particles cost over 40 MB. At 100,000 it's over 200 MB, which on a phone or a browser tab is the difference between a smooth game and a crash.
  2. Creation is slow. Every spawn "loads" a sprite. In a real engine that's decoding an image or at least allocating and copying a buffer, in the middle of a frame.
  3. Caches suffer. Even before you run out of memory, touching 40 MB of mostly duplicate data each frame pushes useful data out of the CPU caches.
  4. Changing a sprite means updating every particle. If the art team ships a new spark image, every live spark holds an old copy.

The particles differ only in position and velocity, which is 32 bytes of real information each. Everything else could be stored once per kind.

Structure

classDiagram
    direction LR
    class ParticleSystem {
        -particles List
        +spawn(kind, x, y, vx, vy)
        +tick(dt)
        +render(canvas)
    }
    class ParticleTypeFactory {
        -types Map
        +get(kind) ParticleType
        +size() int
    }
    class ParticleType {
        <<flyweight, immutable>>
        -kind String
        -sprite bytes
        -color String
        +draw(canvas, x, y)
    }
    class Particle {
        <<extrinsic state>>
        -x double
        -y double
        -vx double
        -vy double
        -type ParticleType
        +move(dt)
    }
    ParticleSystem --> ParticleTypeFactory : asks for shared types
    ParticleSystem o--> Particle : many
    Particle --> ParticleType : shares one per kind
    ParticleTypeFactory o--> ParticleType : creates once, caches

Many Particle objects point at a handful of ParticleType objects. The factory guarantees that each kind's ParticleType is created at most once. Drawing passes the extrinsic state (the position) into the flyweight: type.draw(canvas, x, y).

sequenceDiagram
    participant S as ParticleSystem
    participant F as ParticleTypeFactory
    participant T as "ParticleType (spark)"
    S->>F: get("spark")
    F->>F: not cached, load sprite once
    F-->>S: spark type
    S->>F: get("spark")
    F-->>S: same spark type, no loading
    S->>T: draw(canvas, x=120, y=45)
    S->>T: draw(canvas, x=300, y=90)

Participants

ParticipantIn the exampleResponsibility
FlyweightParticleTypeHolds the intrinsic, shared state. Immutable. Its operations take extrinsic state as parameters.
Flyweight factoryParticleTypeFactoryCreates flyweights on demand and returns the existing one for a key that's already been requested. Must be safe under concurrent access if several threads use it.
Context (extrinsic state holder)ParticleThe small per-object record: position, velocity and a reference to its flyweight. Sometimes this is replaced by plain arrays.
ClientParticleSystemGets flyweights from the factory, stores or computes extrinsic state, and passes it in when calling flyweight operations.

Some descriptions also include an "unshared concrete flyweight", an object that implements the same interface but isn't shared (for example, a single special particle with a unique sprite). It's useful when the flyweight interface is part of a composite tree where only some nodes can be shared.

Implementation

Each version below builds 20,000 particles of three kinds through a flyweight factory, checks that only three types exist and that they're shared, checks that the flyweight can't be mutated, moves and draws the particles, and (in Python) measures memory against the naive version with tracemalloc. Java and TypeScript print an informal heap figure but don't assert on it, because garbage-collected heap readings are too noisy to make a reliable test.

import java.util.*;
import java.util.concurrent.*;

// Flyweight: intrinsic, shared, immutable.
final class ParticleType {
    private final String kind;
    private final byte[] sprite;          // never exposed, so nobody can mutate it
    private final String color;

    ParticleType(String kind, byte[] sprite, String color) {
        this.kind = kind;
        this.sprite = sprite.clone();
        this.color = color;
    }

    String kind() { return kind; }
    int spriteBytes() { return sprite.length; }

    // Extrinsic state (position) comes in as parameters.
    void draw(List<String> canvas, double x, double y) {
        canvas.add(kind + "@" + Math.round(x) + "," + Math.round(y) + " " + color);
    }
}

// Flyweight factory: one instance per key, safe under concurrent access.
final class ParticleTypeFactory {
    static final int SPRITE_BYTES = 2048;
    private static final Map<String, String> COLORS =
            Map.of("spark", "#ffd34d", "smoke", "#888888", "ember", "#ff5a1f");
    private final ConcurrentHashMap<String, ParticleType> types = new ConcurrentHashMap<>();
    final java.util.concurrent.atomic.AtomicInteger loads = new java.util.concurrent.atomic.AtomicInteger();

    ParticleType get(String kind) {
        // computeIfAbsent runs the loader at most once per key, even with racing threads.
        return types.computeIfAbsent(kind, k -> {
            String color = COLORS.get(k);
            if (color == null) throw new IllegalArgumentException("unknown particle kind " + k);
            loads.incrementAndGet();
            byte[] sprite = new byte[SPRITE_BYTES];
            Arrays.fill(sprite, (byte) k.hashCode());     // pretend: decode a PNG
            return new ParticleType(k, sprite, color);
        });
    }

    int size() { return types.size(); }
}

// Context: the small, per-particle extrinsic state plus a reference to the shared type.
final class Particle {
    double x, y;
    final double vx, vy;
    final ParticleType type;

    Particle(ParticleType type, double x, double y, double vx, double vy) {
        this.type = type; this.x = x; this.y = y; this.vx = vx; this.vy = vy;
    }

    void move(double dt) { x += vx * dt; y += vy * dt; }
    void draw(List<String> canvas) { type.draw(canvas, x, y); }
}

class Demo {
    public static void main(String[] args) throws Exception {
        ParticleTypeFactory factory = new ParticleTypeFactory();
        String[] kinds = {"spark", "smoke", "ember"};
        Random rng = new Random(7);

        Runtime rt = Runtime.getRuntime();
        System.gc();
        long before = rt.totalMemory() - rt.freeMemory();

        List<Particle> particles = new ArrayList<>();
        for (int i = 0; i < 20_000; i++) {
            ParticleType t = factory.get(kinds[rng.nextInt(kinds.length)]);
            particles.add(new Particle(t, rng.nextDouble() * 800, rng.nextDouble() * 600,
                    rng.nextDouble() * 2 - 1, rng.nextDouble() * 2 - 1));
        }

        System.gc();
        long after = rt.totalMemory() - rt.freeMemory();

        // Only three flyweights, loaded once each, shared by every particle of that kind.
        assert factory.size() == 3;
        assert factory.loads.get() == 3;
        assert factory.get("spark") == factory.get("spark");
        Set<ParticleType> distinct = Collections.newSetFromMap(new IdentityHashMap<>());
        particles.forEach(p -> distinct.add(p.type));
        assert distinct.size() == 3;

        // Extrinsic state is per particle and changes freely.
        Particle p = particles.get(0);
        double oldX = p.x;
        p.move(10);
        assert p.x == oldX + p.vx * 10;
        List<String> canvas = new ArrayList<>();
        particles.subList(0, 3).forEach(q -> q.draw(canvas));
        assert canvas.size() == 3;

        // Thread safety: racing threads still get one instance per key.
        ParticleTypeFactory shared = new ParticleTypeFactory();
        ExecutorService pool = Executors.newFixedThreadPool(8);
        List<Future<ParticleType>> results = new ArrayList<>();
        for (int i = 0; i < 64; i++) results.add(pool.submit(() -> shared.get("ember")));
        Set<ParticleType> seen = Collections.newSetFromMap(new IdentityHashMap<>());
        for (Future<ParticleType> f : results) seen.add(f.get());
        pool.shutdown();
        assert seen.size() == 1 && shared.loads.get() == 1;

        try { factory.get("confetti"); throw new AssertionError("expected rejection"); }
        catch (IllegalArgumentException expected) { }

        // Informal only: heap readings vary with GC timing, so this is printed, not asserted.
        System.out.printf("flyweight ok: 20,000 particles, 3 types, roughly %.1f MB of heap growth%n",
                (after - before) / 1e6);
    }
}
import dataclasses
import random
import threading
import tracemalloc
from concurrent.futures import ThreadPoolExecutor

SPRITE_BYTES = 2048
COLORS = {"spark": "#ffd34d", "smoke": "#888888", "ember": "#ff5a1f"}


def load_sprite(kind: str) -> bytes:
    """Pretend to decode a PNG from disk. Returns a NEW bytes object every call."""
    return bytes([sum(map(ord, kind)) % 256]) * SPRITE_BYTES


@dataclasses.dataclass(frozen=True, slots=True)
class ParticleType:
    """Flyweight: intrinsic, shared, immutable."""
    kind: str
    sprite: bytes
    color: str

    def draw(self, canvas: list[str], x: float, y: float) -> None:
        canvas.append(f"{self.kind}@{x:.0f},{y:.0f} {self.color}")


class ParticleTypeFactory:
    """Flyweight factory: one instance per key, safe under concurrent access."""

    def __init__(self) -> None:
        self._types: dict[str, ParticleType] = {}
        self._lock = threading.Lock()
        self.loads = 0

    def get(self, kind: str) -> ParticleType:
        found = self._types.get(kind)           # fast path, no lock once warm
        if found is not None:
            return found
        with self._lock:
            found = self._types.get(kind)       # someone may have created it while we waited
            if found is None:
                if kind not in COLORS:
                    raise ValueError(f"unknown particle kind {kind}")
                self.loads += 1
                found = ParticleType(kind, load_sprite(kind), COLORS[kind])
                self._types[kind] = found
            return found

    def __len__(self) -> int:
        return len(self._types)


class Particle:
    """Context: the small, per-particle extrinsic state plus a reference to the shared type."""
    __slots__ = ("type", "x", "y", "vx", "vy")

    def __init__(self, ptype: ParticleType, x: float, y: float, vx: float, vy: float) -> None:
        self.type, self.x, self.y, self.vx, self.vy = ptype, x, y, vx, vy

    def move(self, dt: float) -> None:
        self.x += self.vx * dt
        self.y += self.vy * dt

    def draw(self, canvas: list[str]) -> None:
        self.type.draw(canvas, self.x, self.y)


class NaiveParticle:
    """The 'before' design, kept here so we can measure against it."""
    __slots__ = ("kind", "sprite", "color", "x", "y", "vx", "vy")

    def __init__(self, kind: str, x: float, y: float, vx: float, vy: float) -> None:
        self.kind, self.sprite, self.color = kind, load_sprite(kind), COLORS[kind]
        self.x, self.y, self.vx, self.vy = x, y, vx, vy


def measure(build):
    """Bytes allocated (and still live) while building, plus the built objects."""
    tracemalloc.start()
    built = build()
    used, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return used, built


def spawn_args(n: int, seed: int = 7):
    rng = random.Random(seed)
    kinds = list(COLORS)
    return [(rng.choice(kinds), rng.random() * 800, rng.random() * 600,
             rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]


if __name__ == "__main__":
    args = spawn_args(20_000)
    factory = ParticleTypeFactory()

    naive_bytes, naive = measure(lambda: [NaiveParticle(*a) for a in args])
    shared_bytes, particles = measure(
        lambda: [Particle(factory.get(k), x, y, vx, vy) for k, x, y, vx, vy in args])

    # Sharing: three flyweights, loaded once each.
    assert len(factory) == 3 and factory.loads == 3
    assert factory.get("spark") is factory.get("spark")
    assert len({id(p.type) for p in particles}) == 3

    # Immutability: a shared object must not be changeable by one of its users.
    try:
        particles[0].type.color = "#000000"          # type: ignore[misc]
        raise AssertionError("flyweight should be frozen")
    except dataclasses.FrozenInstanceError:
        pass

    # Extrinsic state moves freely, per particle.
    p = particles[0]
    old_x = p.x
    p.move(10)
    assert p.x == old_x + p.vx * 10
    canvas: list[str] = []
    for q in particles[:3]:
        q.draw(canvas)
    assert len(canvas) == 3

    # Thread safety: racing threads still get one instance per key.
    racing = ParticleTypeFactory()
    with ThreadPoolExecutor(max_workers=8) as pool:
        results = list(pool.map(lambda _: racing.get("ember"), range(64)))
    assert len({id(r) for r in results}) == 1 and racing.loads == 1

    # The measurement that justifies the pattern. Keep it in the test.
    assert shared_bytes * 4 < naive_bytes, (shared_bytes, naive_bytes)
    print(f"naive {naive_bytes / 1e6:.1f} MB, flyweight {shared_bytes / 1e6:.1f} MB, "
          f"{naive_bytes / shared_bytes:.0f}x smaller")
import assert from "node:assert/strict";

const SPRITE_BYTES = 2048;
const COLORS: Readonly<Record<string, string>> = {
  spark: "#ffd34d",
  smoke: "#888888",
  ember: "#ff5a1f",
};

// Flyweight: intrinsic, shared, immutable.
class ParticleType {
  readonly #sprite: Uint8Array; // private, never exposed, so nobody can mutate it
  constructor(readonly kind: string, sprite: Uint8Array, readonly color: string) {
    this.#sprite = sprite.slice();
    Object.freeze(this);
  }
  get spriteBytes(): number {
    return this.#sprite.length;
  }
  // Extrinsic state (position) comes in as parameters.
  draw(canvas: string[], x: number, y: number): void {
    canvas.push(`${this.kind}@${Math.round(x)},${Math.round(y)} ${this.color}`);
  }
}

// Flyweight factory: one instance per key. A single JS thread needs no lock.
class ParticleTypeFactory {
  private readonly types = new Map<string, ParticleType>();
  loads = 0;
  get(kind: string): ParticleType {
    let t = this.types.get(kind);
    if (!t) {
      const color = COLORS[kind];
      if (color === undefined) throw new RangeError(`unknown particle kind ${kind}`);
      this.loads++;
      t = new ParticleType(kind, new Uint8Array(SPRITE_BYTES).fill(kind.length), color);
      this.types.set(kind, t);
    }
    return t;
  }
  get size(): number {
    return this.types.size;
  }
}

// Context: the small, per-particle extrinsic state plus a reference to the shared type.
class Particle {
  constructor(
    readonly type: ParticleType,
    public x: number,
    public y: number,
    readonly vx: number,
    readonly vy: number,
  ) {}
  move(dt: number): void {
    this.x += this.vx * dt;
    this.y += this.vy * dt;
  }
  draw(canvas: string[]): void {
    this.type.draw(canvas, this.x, this.y);
  }
}

// Small deterministic PRNG so runs are repeatable.
let seed = 7;
const rand = (): number => ((seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31);

const factory = new ParticleTypeFactory();
const kinds = Object.keys(COLORS);
const heapBefore = process.memoryUsage().heapUsed;
const particles: Particle[] = [];
for (let i = 0; i < 20_000; i++) {
  const t = factory.get(kinds[Math.floor(rand() * kinds.length)]!);
  particles.push(new Particle(t, rand() * 800, rand() * 600, rand() * 2 - 1, rand() * 2 - 1));
}
const heapAfter = process.memoryUsage().heapUsed;

assert.equal(factory.size, 3);
assert.equal(factory.loads, 3);
assert.equal(factory.get("spark"), factory.get("spark"));
assert.equal(new Set(particles.map((p) => p.type)).size, 3);

// Immutability: the flyweight is frozen, so writes are refused (in strict mode they throw).
const spark = factory.get("spark");
assert.ok(Object.isFrozen(spark));
assert.equal(Reflect.set(spark, "color", "#000000"), false);
assert.equal(spark.color, "#ffd34d");

const p = particles[0]!;
const oldX = p.x;
p.move(10);
assert.equal(p.x, oldX + p.vx * 10);
const canvas: string[] = [];
particles.slice(0, 3).forEach((q) => q.draw(canvas));
assert.equal(canvas.length, 3);
assert.throws(() => factory.get("confetti"), RangeError);

// Informal only: heap readings depend on GC timing, so this is printed, not asserted.
console.log(
  `flyweight ok: 20,000 particles, 3 types, roughly ${((heapAfter - heapBefore) / 1e6).toFixed(1)} MB heap growth`,
);

Walking through it

The split is the design. ParticleType holds what's the same for every spark: the kind, the sprite and the colour. Particle holds what's different: four numbers and a reference. Finding that split is the real work. The code that follows from it is short.

The factory is what makes sharing reliable. Without it, nothing stops code from writing new ParticleType(...) in ten places and ending up with ten copies of the spark sprite. The factory is the only place types are created, and it returns the cached one for any kind it has seen. That's why it's usually paired with a private or package-private constructor in Java, so code outside can't bypass it.

Immutability isn't optional. Twenty thousand particles share three objects. If one particle could set type.color = "#000000", every spark in the game would turn black. The Java version uses final fields and never hands out the sprite array. The Python version uses a frozen dataclass, and the demo checks that assignment raises. The TypeScript version freezes the object and keeps the sprite in a private field. If a flyweight needs to look different for one particle (a tint, for example), that's extrinsic state: pass it in, don't store it.

Thread safety lives in the factory. The flyweights themselves are immutable, so any number of threads can read them without locks. The factory is the shared mutable structure. Java's ConcurrentHashMap.computeIfAbsent runs the loader at most once per key even when threads race, which the demo checks with 64 concurrent requests. The Python version uses a double-checked lock: a lock-free read for the common warm case, then a lock and a second check before creating. In JavaScript, one thread runs your code, so a plain Map is enough. Worker threads don't share ordinary objects, so each worker would have its own factory.

The factory can grow forever. Here the keys are a fixed set of three, so that's fine. If keys come from user input (font names, arbitrary strings), an unbounded factory is a memory leak. Bound it, evict with an LRU policy, or use weak references so unused flyweights can be collected (WeakHashMap keys in Java hold the key weakly, which isn't the same thing. You'd need weak values, which Python's weakref.WeakValueDictionary provides directly).

Measure before you use it

The Python sample prints something like "naive 43.6 MB, flyweight 1.6 MB" (exact figures vary by Python version and platform) and asserts that the flyweight version is at least four times smaller. That assertion is the most important line on this page. Flyweight adds a factory, a split between two classes, and the rule that a whole category of objects must be immutable. That's worth paying only when memory is actually the problem and the shared state is actually large.

Before applying the pattern, find out:

  1. How many objects exist at peak? Thousands of objects rarely matter. Hundreds of thousands or millions might. Count them with a heap profiler, not a guess.
  2. How big is the shared part compared with the unique part? If each object holds 2 KB of shared data and 32 bytes of unique data, sharing removes almost all of it. If each holds 16 bytes shared and 64 unique, sharing saves a fifth at best, and the reference to the flyweight costs part of that back.
  3. Is memory the real bottleneck? If the program is CPU-bound or I/O-bound, saving memory makes it no faster. Sometimes it's slower, because of the extra lookup and indirection.
  4. What does the runtime already do? Java interns string literals and caches small boxed integers, CPython caches small ints and interns many identifier-like strings, and V8 shares hidden classes between objects with the same shape. You may already be getting the benefit.

The tools to use:

  • Python: tracemalloc (as in the demo), sys.getsizeof for a single object's shallow size, or a profiler such as memray.
  • Java: a heap dump analysed with Eclipse MAT or VisualVM, JDK Flight Recorder allocation profiling, or the JOL (Java Object Layout) library to see exact object sizes. On a typical 64-bit HotSpot JVM, an object header is 12 bytes with compressed class pointers, and objects are padded to 8-byte boundaries, so small objects cost more than their fields suggest.
  • Node.js and browsers: heap snapshots in Chrome DevTools or node --inspect, and process.memoryUsage() for rough trends.

Measure after the change too, under the same workload, and keep the measurement as a test or benchmark if the saving matters. Optimisations that aren't checked tend to erode as the code changes.

Sometimes the better answer is no objects at all

Flyweight still leaves one small object per particle. When counts reach millions, even that overhead dominates: every Python object has a header and every float is a separate object. Game engines and data-heavy code often go one step further and store extrinsic state in parallel arrays ("structure of arrays"), keeping only the flyweights as objects. The sample below measures objects-with-flyweights against arrays-with-flyweights for the same 20,000 particles.

import random
import tracemalloc
from array import array

N = 20_000
KINDS = ["spark", "smoke", "ember"]          # index into this list = the flyweight key


class Particle:
    __slots__ = ("kind", "x", "y", "vx", "vy")

    def __init__(self, kind: int, x: float, y: float, vx: float, vy: float) -> None:
        self.kind, self.x, self.y, self.vx, self.vy = kind, x, y, vx, vy


def measure(build):
    tracemalloc.start()
    built = build()
    used, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return used, built


def spawn(seed: int = 7):
    """The same random particles every time, generated inside each build so both pay for them."""
    rng = random.Random(seed)
    for _ in range(N):
        yield (rng.randrange(3), rng.random() * 800, rng.random() * 600,
               rng.uniform(-1, 1), rng.uniform(-1, 1))


objects_bytes, objs = measure(lambda: [Particle(*r) for r in spawn()])


def build_columns():
    cols = {"kind": array("B"), "x": array("d"), "y": array("d"), "vx": array("d"), "vy": array("d")}
    for kind, x, y, vx, vy in spawn():
        cols["kind"].append(kind)       # 1 byte per particle
        cols["x"].append(x)             # 8 bytes per particle, no float objects kept
        cols["y"].append(y)
        cols["vx"].append(vx)
        cols["vy"].append(vy)
    return cols


columns_bytes, cols = measure(build_columns)

# Moving every particle is one loop over flat arrays.
x, vx = cols["x"], cols["vx"]
for i in range(N):
    x[i] += vx[i] * 10
assert abs(x[0] - (objs[0].x + objs[0].vx * 10)) < 1e-9
assert KINDS[cols["kind"][0]] == KINDS[objs[0].kind]

assert columns_bytes * 3 < objects_bytes, (columns_bytes, objects_bytes)
print(f"objects {objects_bytes / 1e6:.2f} MB, columns {columns_bytes / 1e6:.2f} MB")

The arrays use several times less memory again, and a loop over a flat array of doubles is friendly to CPU caches (and to NumPy, if you use it). The cost is that you lose the object-oriented interface: there's no particle.move(), only index-based loops. That trade-off is worth knowing exists, and worth mentioning in an interview when someone asks how far you'd take a memory optimisation.

Flyweights built into the platform

Java and Python both use flyweights for common immutable values, and knowing the details prevents a classic bug: comparing objects with == (Java) or is (Python) and having it work only for small values.

class Demo {
    public static void main(String[] args) {
        // Integer.valueOf caches -128..127 (the range the language spec requires for boxing).
        Integer a = Integer.valueOf(127), b = Integer.valueOf(127);
        Integer c = Integer.valueOf(128), d = Integer.valueOf(128);
        assert a == b : "same cached instance";
        assert c != d : "outside the default cache, two different objects";
        assert c.equals(d) : "which is why you compare boxed values with equals";

        // Boolean.valueOf always returns one of two shared instances.
        assert Boolean.valueOf("true") == Boolean.TRUE;

        // String literals are interned; new String(...) is not, until you intern it.
        String literal = "spark";
        String built = new String("spark");
        assert literal != built;
        assert literal == built.intern();
        assert literal == ("spa" + "rk") : "compile-time constant, interned too";

        System.out.println("JDK flyweights behave as expected");
    }
}
import sys

# sys.intern returns one shared string object per distinct value.
a = sys.intern("".join(["spa", "rk"]))
b = sys.intern("sp" + "ark".lower())
assert a is b

# Strings built at runtime are not interned automatically.
c = "".join(["spa", "rk"])
d = "".join(["spa", "rk"])
assert c == d
if sys.implementation.name == "cpython":
    assert c is not d

    # CPython caches small ints (-5..256). This is an implementation detail, not a language rule.
    assert int("256") is int("256")
    assert int("257") is not int("257")

# None, True and False are singletons in every implementation, so `is` is correct for them.
assert (1 > 0) is True
print("Python flyweights behave as expected")

The lessons:

  • Never compare boxed numbers or strings by identity. In Java, Integer values compare equal with == up to 127 and then stop, which produces bugs that only show up in production with larger IDs. Use equals. In Python, use == for values and keep is for None, True, False and sentinel objects. (CPython emits a SyntaxWarning for is with a literal for this reason.)
  • The Java cache range can be raised. HotSpot's -XX:AutoBoxCacheMax increases the upper bound of the Integer cache. That's another reason not to rely on the default boundary in either direction.
  • Interning is a flyweight factory with the string value as the key. String.intern() and sys.intern() look up the value in a table and return the canonical instance. That helps when you hold millions of copies of a few distinct strings (country codes, status values, column names read from a file), and it also turns string equality into a cheap identity check internally. It doesn't help, and wastes table space, when most strings are unique.
  • Modern JVMs can deduplicate for you. The G1 collector supports string deduplication (-XX:+UseStringDeduplication), which shares the underlying character arrays of equal strings during GC without any code change. Check what the runtime offers before hand-rolling interning.

Real-world uses

JDK

  • Integer.valueOf, Short.valueOf, Byte.valueOf, Long.valueOf and Character.valueOf return cached instances for small values, and autoboxing goes through these methods. Boolean.valueOf returns Boolean.TRUE or Boolean.FALSE.
  • The string pool: string literals and compile-time constant expressions are interned, and String.intern() adds others.
  • Enum constants are the extreme flyweight: a fixed set of instances, created once, shared everywhere, and compared safely with ==.
  • Swing's table and list cell renderers. A JTable doesn't create a component per cell. It asks one renderer component to configure itself for a cell, paints it at that cell's position, and reuses it for the next cell. The renderer is shared, and the cell value and position are extrinsic.

Python

  • sys.intern, and CPython's automatic interning of many identifier-like string constants (attribute names, dictionary keys used as names), which speeds up attribute and name lookups.
  • The CPython small-integer cache (-5 to 256), an implementation detail rather than a language guarantee.
  • None, True, False, Ellipsis and NotImplemented are single shared instances.

Engines, editors and runtimes

  • Text rendering. Font rasterisers and text editors cache one glyph bitmap or outline per (character, font, size) combination and draw it at many positions. The glyph is intrinsic, and the position and colour are extrinsic. The original design-patterns book used glyphs in a document editor as its main Flyweight example.
  • GPU instanced rendering in game engines draws one mesh and material many times with per-instance transforms, which is the same split at the graphics-API level.
  • Tile maps in 2D games store each tile image once and the map as a grid of small tile indices.
  • V8 hidden classes. Objects created with the same property layout share one hidden class (V8 calls it a map) describing their shape, rather than each object storing its own property-name table. It's an engine-internal optimisation, but it's flyweight thinking.

When NOT to use it

When you haven't measured. This is the main one. Without a heap profile showing many duplicate objects and a meaningful share of memory in them, Flyweight is complexity for an imagined problem.

When object counts are modest. A few thousand objects, each with some shared data, almost never justify the pattern on a modern machine. The saving is real but irrelevant.

When the shared part is small. If the intrinsic state is a couple of short fields, the reference to the flyweight plus the factory lookup can cost nearly as much as it saves.

When the "shared" state isn't really immutable. If objects of the same kind sometimes need different values for the "shared" fields, you'll be tempted to mutate the flyweight, and that changes every object that shares it. Either that state is extrinsic, or the objects aren't really the same kind.

When identity matters to the domain. Flyweights are interchangeable by design: two sparks share one ParticleType. If the domain needs per-object identity for the shared part (each glyph tracks its own edit history, each tile can be individually damaged), it isn't intrinsic.

When the extrinsic state is expensive to compute or pass. The pattern assumes the client can cheaply supply the context to each call. If computing a particle's position for each draw call is costly, or if passing context through many layers clutters every signature, the code gets harder to follow.

When simpler memory fixes exist. __slots__ in Python, primitive arrays instead of boxed collections in Java, typed arrays in JavaScript, dropping unused fields, or loading data lazily often save as much with less design impact.

The costs, listed: a factory to maintain (and to make thread-safe and bounded), a split of one concept into two classes, every method that needs context taking extra parameters, the immutability rule for shared state, and identity-comparison pitfalls for anyone who doesn't know objects are shared.

PatternWhat's shared or reusedMutable?Number of instances
FlyweightIntrinsic state, shared by many users at the same timeNo, must be immutableOne per distinct key
SingletonOne object for the whole programOften yesExactly one
Object PoolExpensive objects, reused one user at a timeYes, reset between usesA fixed or bounded pool
PrototypeNothing shared after creation; new objects are copied from a templateYesAs many as you clone
CompositeLeaf nodes can be flyweightsDependsTree of many nodes
Proxy (caching)Results of callsUsually immutable resultsOne proxy per subject

Flyweight vs Singleton. A singleton is one instance of a class for the whole program. A flyweight factory produces one instance per key, so there may be three or three thousand. Singletons are often mutable and act as global access points, while flyweights must be immutable and are passed around like values. A flyweight factory is sometimes itself a singleton, but it doesn't need to be.

Flyweight vs Object Pool. Both reuse objects to save resources, and they're often confused. A pool hands out an object for exclusive use (a database connection, a large buffer) and takes it back afterwards, resetting its state. A flyweight is used by many clients simultaneously and never changes. If two users holding the same instance at once would be a bug, you want a pool. If it's the point, you want a flyweight.

Flyweight vs caching and memoisation. A flyweight factory is a cache keyed by intrinsic state. The difference is intent: a memoising cache saves computation by returning the same result for the same input, while a flyweight factory saves memory by ensuring one shared instance. In practice the code looks the same, and the same concerns apply (bounding, eviction, thread safety).

Flyweight and Composite. Leaf nodes of a composite can be flyweights. In a document tree, every "e" character can point to one shared glyph. The catch is that a shared leaf can't store a parent pointer, because it has many parents. The parent becomes extrinsic, passed down during traversal.

Flyweight and State or Strategy. Stateless state and strategy objects (ones with no fields) can be shared by every context that uses them, which makes them flyweights for free. Enum-based state machines in Java do exactly this.

Flyweight and value objects. Immutable value objects (money amounts, dates, colours) are natural flyweight candidates when there are few distinct values and many copies. Interning them through a factory is the pattern applied to a domain type.

The smell that suggests it

  • A heap profile dominated by many instances of the same class, where most fields hold equal values across instances. That's the signal, and you get it from a profiler, not from reading code.
  • Large immutable data copied into each object: images, textures, lookup tables, configuration blobs, font data, the same long strings.
  • Memory growing linearly with the number of entities (particles, map tiles, document characters, rows of a grid) when the number of distinct kinds is small.
  • Repeated loading of the same resource at object-creation time, like load_sprite(kind) inside a constructor.
  • Millions of short strings with few distinct values, such as status codes or country codes parsed from a file.

The counter-smells: there's no measurement, the number of objects is small, or the "shared" fields keep needing per-object exceptions.

Interview questions

  1. "What's the difference between intrinsic and extrinsic state? Give an example." Intrinsic state is context-independent and shared across many objects, so it lives in the flyweight and must be immutable: a glyph's outline in a given font, a particle type's sprite. Extrinsic state depends on context and differs per use, so the client stores it and passes it in: the glyph's position on the page, the particle's position and velocity.

  2. "Why must flyweights be immutable?" Because many clients hold the same instance at once. If one client changes it, every other client sees the change: one particle changes its colour and every particle of that kind changes. Immutability also makes flyweights safe to share across threads without locks.

  3. "How do you make a flyweight factory thread-safe?" Use an atomic get-or-create: ConcurrentHashMap.computeIfAbsent in Java, or a lock with a double check in Python. Make sure the creation function runs at most once per key, or at least that only one result is ever published. The flyweights themselves need no locking because they're immutable.

  4. "Is Integer.valueOf(1000) == Integer.valueOf(1000) true in Java?" Not with default settings. Boxing caches only -128 to 127 by default (the range the language specification requires), so 1000 gives two different objects and == compares references. equals is correct. The cache's upper bound can be raised with a JVM flag, which is another reason not to depend on it.

  5. "Design the data model for a text editor that can hold a 10-million-character document." Characters share glyph flyweights from a factory keyed by (character, font, size, style). The document stores the text compactly (for example a rope or piece table of code points), with style runs rather than per-character style objects, and computes layout positions as extrinsic state when rendering visible lines. Mention that you'd profile first, and that rendering only the visible region matters as much as sharing glyphs.

  6. "Flyweight vs Object Pool?" A pool lends an object to one user at a time and resets it on return, which suits expensive mutable resources such as connections or buffers. A flyweight is shared by many users simultaneously and never changes. Simultaneous sharing is a bug for pooled objects and the whole point for flyweights.

  7. "Your flyweight factory keys on user-supplied strings. What's the risk?" Unbounded growth, which is a memory leak and possibly a denial-of-service vector. Bound the cache, evict least-recently-used entries, or hold values weakly (weakref.WeakValueDictionary in Python) so unused flyweights can be collected. Validate keys against a known set where possible.

  8. "How would you prove the pattern helped?" Measure memory before and after under the same workload: tracemalloc in Python, a heap dump or JFR in Java, heap snapshots in Node. Compare peak or retained size, check that the count of the duplicated class dropped, and check that CPU time didn't get worse because of lookups. Keep a benchmark or test with a safe margin so the gain doesn't silently regress.

  9. "When would you go beyond Flyweight?" When even one small object per entity is too much, store extrinsic state in parallel primitive arrays (structure of arrays), keeping only the shared types as objects. That's common in game engines and numeric code, and it trades the object interface for much lower memory use and better cache behaviour.

  10. "Where does Flyweight show up in real systems?" String interning in Java and Python, boxed integer caches, enum constants, Swing cell renderers, glyph caches in font rendering and text editors, tile maps and instanced rendering in games, and V8's hidden classes shared across objects with the same shape.