How can I get the size in bytes of the following Map?
const cache = new Map();
cache.set("1", { id: "1" });
How can I get the size in bytes of the following Map?
const cache = new Map();
cache.set("1", { id: "1" });
Map object does not define default stringification, that is, JSON.stringify
will not work on it by default, nor mapObj.toString()
will return a meaningful answer. Therefore, you need to define how to turn a Map to a string, so that you can estimate its size.
Building on this great answer:
function mapSize(oMap){
function replacer(key, value) {
if(value instanceof Map) {
return {
dataType: 'Map',
value: [...value],
};
} else {
return value;
}
}
return JSON.stringify(oMap, replacer).length;
}
let test= new Map([["a",2],["b",3]]);
console.log(mapSize(test)); //44
This will return something you can use to approximate. Beware that 'dataType' and 'value' fields are arbitrary, and they effect the 'size'.