O'Reilly logo

Python Unlocked by Arun Tigeraniya

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Flyweight pattern

Key 7: Consuming less memory with shared objects.

A flyweight design pattern is useful to save memory. When we have lots of object count, we store references to previous similar objects and provide them instead of creating new objects. In the following example, we have a Link class used by the browser, which stores the link data.

The browser uses this data, and there may be a lot of data that is associated with pictures referenced by the link, such as image content, size, and so on, and images can be reused over the page. Hence, the nodes using it only store a flyweight BrowserImage object to decrease the memory footprint. When the link class tries to create a new BrowserImage instance, the BrowserImage class checks whether it ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required