r/ProgrammerTIL • u/c0d3m0nky • Mar 15 '18
Javascript [Javascript] TIL MomentJS objects are huge on memory footprint
tl;dr Don't keep mass quantities of moment instances in memory, they're HUGE. Instead use someDate.unix() to store then moment.unix(storedEpoch) to retrieve when you actually need the moment instance;
I had to throw together some node to parse huge logs and rebuild reporting data that needed to get all the data structure then analyzed in the order they happened, so I was storing millions of dates. I had to do date math so I stored the raw moment objects. Well less than a quarter of the way through node was dragging to a halt using 2gb+ of memory. I changed it to use moment.unix and just instantiated the numbers back to moment as I needed them and the whole thing ran to completion staying under 500mb.
Running this, memory usage was ~433mb
let moment = require('moment');
let arr = [];
for(let i = 0; i < 1010000; i++) arr.push(moment());
Running this, memory usage was ~26mb
let moment = require('moment');
let arr = [];
for(let i = 0; i < 1010000; i++) arr.push(moment().unix());
A coworker asked "What about Date?" So...
Running this, memory usage was ~133mb
let moment = require('moment');
let arr = [];
for(let i = 0; i < 1010000; i++) arr.push(moment().toDate());
Good call /u/appropriateinside, it was late and I was tired, lol
Edit 1: correcting typos
Edit 2: Added example with memory usage
Edit 2: Added example using Date
View all comments
Show parent comment
2
u/c0d3m0nky Apr 18 '18
Not in production code. In node, if we have to deal with this much data we use streams. In this case I was parsing through almost a gig of webserver logs looking for evidence of an issue and needed to analyze everything together but was too lazy to dump the data into sqlite. Our QA keeps chastising me for not using python but I love js too much not to use it as my scripting language too lol