Flyweight Pattern: Saving Memory Like a Pro

Is your app crashing under the weight of too many objects? Learn how the Flyweight pattern uses memory sharing to handle thousands of instances efficiently.

April 22, 20242 min read3 / 4

The Flyweight Pattern is all about being smart with space. It's the go-to pattern when you need to handle thousands (or millions) of objects without running out of RAM.

The Problem: The 500MB Bullet Crash

Imagine you are making a game like PUBG. There are 250,000 bullets flying around the map!

Each bullet has:

  1. Heavy Stuff (Intrinsic): A 2KB 3D image of the bullet (this never changes).
  2. Light Stuff (Extrinsic): Its location (X, Y, Z) and direction (this changes every second).

If every bullet stores its own 2KB image, you will use 500MB of RAM! This will crash any mobile game.

The Solution: Share the Heavy Stuff

Flyweight says: "Keep one copy of the heavy image and let all 250,000 bullets point to it."

Implementation (Java Focus)

We split the data into two classes:

  1. The Flyweight (BulletType): Stores the shared, immutable data.
  2. The Client (FlyingBullet): Stores the unique, changing data.
Java
// The Heavy Part (Stored once in a Registry) public class BulletType { private byte[] image; // 2KB private int damage; } // The Light Part (Created thousands of times) public class FlyingBullet { private double x, y, z; private BulletType type; // Just a tiny pointer! }

Java vs. JavaScript: The Memory Reality

1. In Java (Explicit Memory Management)

Java developers use Flyweight frequently in high-performance systems. A famous example is Java's Integer Cache. When you use Integer.valueOf(5), Java doesn't create a new object; it returns a cached "Flyweight" integer from an internal pool to save memory!

2. In JavaScript / TypeScript

In modern JS, memory is often managed by the engine (V8), but Flyweight is still relevant for large-scale data visualization or games (e.g., using Three.js). By sharing geometries and materials across thousands of meshes, you can achieve 60FPS on a browser.


Summary Cheat Sheet

  • When to use: You have a huge number of objects that share identical, immutable data.
  • Key Concept: Split state into Intrinsic (shared) and Extrinsic (unique).
  • Benefit: Massive reduction in memory footprint and garbage collection overhead.

Great job! You've now mastered the major Structural patterns. In our next module, we move to Behavioral Patterns, starting with the Strategy Pattern.