When does using Flyweight become inefficient?
Using Flyweight becomes inefficient when there is too much extrinsic state or shared data does not repeat often enough - then the cost of managing the templates outweighs the benefit.
1. When Most Objects Are Unique
If objects have almost no shared state (all of them differ across dozens of parameters), creating and maintaining a pool of flyweights delivers no savings and only adds overhead.
Example: if every tree has a unique texture and color, storing "shared"
TreeTypeobjects makes no sense.
2. When There Is Too Much Extrinsic State
Flyweight requires unique data (coordinates, name, state) to be passed in from outside. If there is a lot of this data, then:
- the code becomes more complex - you have to pass long argument lists;
- the objects stop being "lightweight";
- performance drops because of frequent access to external structures.
3. High Cost of Lookup and Storage in the Pool
If the cache is too large (tens of thousands of entries), looking up the right flyweight in the collection (especially with a poor key) can become more expensive than creating a new object.
4. Thread-Safety Problems
Shared flyweight objects are used by many threads, and with incorrect synchronization, races and locking arise, slowing the system down.
5. Reduced Readability and Growing Complexity
Passing extrinsic state into every call complicates the code and makes it less obvious:
treeType.draw(x, y, rotation, windSpeed, humidity);Sometimes it is simpler to store everything in a single object.
Conclusion
Flyweight is inefficient when:
- the share of shared data is small,
- managing the pool is more complex than creating objects,
- there is too much extrinsic state or too many threads.
Summary: Flyweight is useful for mass data duplication, but in systems with highly unique objects it only complicates the architecture and reduces performance.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.