Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
js-string-memory-usage
// node --max-old-space-size=100 --expose-gc index.js
const prettyBytes = require('pretty-bytes');
const forceGC = () => {
if (global.gc) {
global.gc();
} else {
console.warn('No GC hook! Start your program as `node --expose-gc file.js`.');
}
}
const memoryUsage = () => {
forceGC();
const used = process.memoryUsage();
return Object.entries(used).reduce((acc, [key, value]) => `${acc}\n${key}: ${prettyBytes(value)}`, '')
}
// const randomString = () => Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
const randomId = (length) => {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log('START:', memoryUsage());
let arr = [];
const allocate = () => {
// 600,000 strings === `100 MB`
// 600,000 numbers === '9.02 MB'
for (var i = 0; i < 750000; i++) {
arr.push(`${randomId(2)}-${randomId(13)}`);
}
}
const unallocate = () => {
arr = undefined;
}
allocate();
// unallocate();
console.log(arr);
console.log('END:', memoryUsage()); // heapUsed is the one to monitor. It will go up *and down with GC*.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment