Created
August 6, 2025 13:04
-
-
Save LeaveAirykson/8772fb2ef5ff119271a8188b5f8a5676 to your computer and use it in GitHub Desktop.
JS Calculate memory size for object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function calcSizeInMemory(obj) { | |
const visited = new Set(); | |
function sizeOf(obj) { | |
if (obj === null || obj === undefined) return 0; | |
switch (typeof obj) { | |
case "number": | |
return 8; | |
case "string": | |
return obj.length * 2; | |
case "boolean": | |
return 4; | |
case "object": | |
if (visited.has(obj)) return 0; | |
visited.add(obj); | |
let bytes = 0; | |
const objClass = Object.prototype.toString.call(obj).slice(8, -1); | |
if (objClass === "Object" || objClass === "Array") { | |
for (const key in obj) { | |
if (!Object.hasOwnProperty.call(obj, key)) continue; | |
bytes += sizeOf(key); // count key size | |
bytes += sizeOf(obj[key]); | |
} | |
} else if (objClass === "Date") { | |
bytes += 8; | |
} else if (objClass === "Set" || objClass === "Map") { | |
for (const item of obj) { | |
bytes += sizeOf(item); | |
} | |
} else if (typeof Buffer !== "undefined" && Buffer.isBuffer(obj)) { | |
bytes += obj.length; | |
} else { | |
bytes += obj.toString().length * 2; | |
} | |
return bytes; | |
default: | |
return 0; | |
} | |
} | |
function formatByteSize(bytes) { | |
if (bytes < 1024) return bytes + " bytes"; | |
else if (bytes < 1048576) return (bytes / 1024).toFixed(3) + " KiB"; | |
else if (bytes < 1073741824) return (bytes / 1048576).toFixed(3) + " MiB"; | |
else return (bytes / 1073741824).toFixed(3) + " GiB"; | |
} | |
return formatByteSize(sizeOf(obj)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment