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
(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(json) | |
.then(function (data) { | |
myUsers = data; | |
console.log('Finished fetching data'); | |
}) | |
} | |
function regularData() { | |
getData('/getData') | |
} | |
function flyWeightData() { | |
getData('/getFlyWeightData'); | |
} | |
let myUsers; | |
document.getElementById('request').addEventListener('click', regularData); | |
document.getElementById('requestFlyWieght').addEventListener('click', flyWeightData); | |
})(); |
<button id="request">Request data</button> | |
<button id="requestFlyWieght">Request light weight data</button> | |
<script src="flyWeight.js"></script> |
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).
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).