Performance Trade-offs in Structural Patterns
What You'll Learn
You'll learn to recognize when the overhead of Facade, Flyweight, and Proxy patterns is acceptable and when it becomes a performance problem.
The Core Idea
Structural patterns organize code beautifully, but they aren't free. Each introduces some cost—whether in memory, CPU cycles, or indirection. The key is knowing when the benefits outweigh the costs.
Facade: When Simplicity Adds Overhead
A Facade simplifies a complex subsystem by providing a unified interface. The trade-off? Every call goes through an extra layer. If your subsystem is already simple or you're making many high-frequency calls, this indirection might hurt performance. However, if the Facade reduces network round-trips, consolidates error handling, or caches results, it can actually improve performance.
Use Facade when: Code clarity and reduced coupling matter more than micro-optimizations, or when the Facade actively optimizes subsystem interactions.
Flyweight: When Memory Savings Justify Complexity
Flyweight shares common state across many objects to save memory. The cost? You must separate intrinsic from extrinsic state and manage a factory. For small numbers of objects, this overhead isn't worth it. But when you have thousands of similar objects (like text characters, game particles, or UI elements), the memory savings are dramatic.
Use Flyweight when: You have many similar objects and memory is constrained—the pattern pays for itself at scale.
Proxy: When Indirection Earns Its Keep
Proxies add a layer between client and real object, introducing method-call overhead. But if your Proxy enables lazy loading (avoiding expensive object creation), implements caching (reducing repeated work), or manages remote communication efficiently, that indirection is worthwhile.
Use Proxy when: The overhead is negligible compared to what you're deferring, caching, or protecting against.
Key Takeaway
Structural patterns have performance costs—Facade adds call indirection, Flyweight requires state management, and Proxy introduces forwarding overhead. Apply them when their benefits (simplicity, memory savings, controlled access) clearly outweigh these costs in your specific context.