Memory on a Diet

Estimated Reading Time: 2 minutes

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:

  1. The naive way – get the object with all its properties
  2. 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.

Figure 1: (1) The memory tab. (2) The Heap snapshot option selected. (3) The button to take a heap snapshot

Let’s compare the memory snapshot between the flyweight and the regular data fetch:

Figure 2: Memory comparison of the regular snapshot (Snapshot 3, marked in orange border) with the flyweight snapshot (Snapshot 2, marked in a blue border).

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).

Summary

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).

Leave a Reply

Your email address will not be published. Required fields are marked *