Memory on a Diet

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
(function() {
function json(response) {
return response.json()
function getData(url) {
fetch(url, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
.then(function (data) {
myUsers = data;
console.log('Finished fetching data');
function regularData() {
function flyWeightData() {
let myUsers;
document.getElementById('request').addEventListener('click', regularData);
document.getElementById('requestFlyWieght').addEventListener('click', flyWeightData);
view raw flyWeight.js hosted with ❤ by GitHub
<button id="request">Request data</button>
<button id="requestFlyWieght">Request light weight data</button>
<script src="flyWeight.js"></script>
view raw index.html hosted with ❤ by GitHub

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


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

Sign up to my newsletter to enjoy more content:

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments