Course contentsShow
← Rust
Lesson 665 of 1,9105. Type System and TraitsFree lesson

Implementing the Flyweight for Resource Reuse

Manage high-volume data structures by sharing common state via traits.

In this lesson, you will learn how to optimize memory usage in high-volume systems by sharing common data across multiple objects using the Flyweight pattern.

The Problem: Memory Bloat

Imagine you are building a game engine where you have 10,000 "Tree" objects in a forest. Each Tree struct contains its own high-resolution texture data and model mesh. If every instance stores these heavy assets, you will quickly exhaust your system's RAM. Most of that data is identical across all instances—only the position (x, y) changes.

The Solution: Separating Intrinsic and Extrinsic State

The Flyweight pattern suggests splitting your data into two categories:

  1. Intrinsic State: Shared, read-only data (like a texture or mesh). This stays in one place.
  2. Extrinsic State: Unique data (like coordinates or individual tree age). This is passed in by the client.

By using an Rc (Reference Counted) pointer or a central factory, we can ensure that all 10,000 trees point to a single shared instance of the heavy texture data.

Implementation Example

Here is how you might structure this in Rust:

use std::rc::Rc;

struct TreeMesh {
    vertices: Vec<f32>,
    texture: Vec<u8>,
}

struct Tree {
    position: (f32, f32),
    mesh: Rc<TreeMesh>, // Shared reference
}

fn main() {
    let shared_mesh = Rc::new(TreeMesh {
        vertices: vec![0.0, 1.0, 0.0],
        texture: vec![255, 0, 255],
    });

    let forest = vec![
        Tree { position: (10.0, 5.0), mesh: Rc::clone(&shared_mesh) },
        Tree { position: (20.0, 8.0), mesh: Rc::clone(&shared_mesh) },
    ];
}

By wrapping the expensive TreeMesh in an Rc, we store the heavy data exactly once in memory. Every Tree struct simply holds a pointer to that shared data. When you have thousands of objects, this approach drastically reduces the memory footprint and improves cache locality, allowing your system to scale far beyond what duplicating the raw data would allow.

Key Takeaway: The Flyweight pattern minimizes memory usage by extracting intrinsic, shared state into a single, reference-counted resource while keeping extrinsic, instance-specific state in the object itself.