Tutorials Design Patterns Mastery

Flyweight Pattern: Drastically reducing memory footprint

On this page

The Flyweight Pattern

The Flyweight Pattern is used to minimize memory usage by sharing as much data as possible with other similar objects. It is the secret behind high-performance gaming engines and text editors that can handle millions of characters with zero lag.

1. Intrinsic vs Extrinsic State

  • Intrinsic: Data that is the same for all objects (e.g., The shapes of the 'A' character in a font). This is Shared.
  • Extrinsic: Data that varies for each object (e.g., The coordinates of 'A' on page 5). This is Unique.

2. Implementation Tip

We use a Flyweight Factory. When you ask for an object, the factory checks if it already has one in memory. If yes, it returns the existing instance. If no, it creates a new one and stores it for the next person.

public class TreeFactory 
{
    private static Dictionary<string, TreeType> _types = new();

    public static TreeType GetTreeType(string name, string color) 
    {
        // If we already have a 'Green Oak', reuse the object!
        if (!_types.ContainsKey(name)) 
            _types[name] = new TreeType(name, color);
            
        return _types[name];
    }
}

4. Interview Mastery

Q: "How does the .NET 'String Intern Pool' implement the Flyweight pattern?"

Architect Answer: ".NET maintains a hidden table (the Intern Pool) for all literal strings. If you have 10,000 variables all set to the string 'Error', the CLR doesn't create 10,000 objects. It creates ONE 'Error' object (the Flyweight) and points all 10,000 variables to that same memory address. This saves significant RAM and makes string comparison (`==`) much faster. This is Flyweight in action at the runtime level."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns Mastery
Course syllabus
1. Introduction to Design Patterns
2. Creational Patterns
3. Structural Patterns
4. Behavioral Patterns
5. Modern Enterprise & Cloud Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details