In my last article, I talked about the flyweight design pattern. I mostly talked about how it can save you (and your end user) bandwidth.
I failed to mention the save on memory.
If we continue the example from the aforementioned blog post, let’s measure the memory consumption.
A short reminder – the client code below fetches data from a server in two ways:
- The naive way – get the object with all its properties
- The Flyweight way – get the object with a type, as well as a type-metadata dictionary
In chrome devtools, there’s the memory tab. With it, we can take a snapshot of our memory in various times and compare them.
Let’s compare the memory snapshot between the flyweight and the regular data fetch:
Figure 2 shows the comparison of total memory allocated by the regular fetch subtracted by the total memory allocated by the flyweight pattern. The difference is roughly 320kb (marked with the red border).
In this short post we saw that by utilizing the Flyweight design pattern, we can reduce the memory signature of our app.
It doesn’t matter if your client is running in the browser or a service that receives data – if big chunks of data have similar properties, you can use the flyweight pattern and reduce both bandwidth and memory usage.
So if your app is currently in the heavy weight category – you can put it on a strict diet to get it to the flyweight category (yes… geek jokes combined with me being a data… a killer).