Skip to content

Instantly share code, notes, and snippets.

@inorganik
Created February 26, 2020 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inorganik/4c446923d269955c46205be9482b2465 to your computer and use it in GitHub Desktop.
Save inorganik/4c446923d269955c46205be9482b2465 to your computer and use it in GitHub Desktop.
Calculate the size of a js object in bytes
export function roughSizeOfObject(object) {
const objectList = [];
const stack = [object];
let bytes = 0;
while (stack.length) {
const value = stack.pop();
if (typeof value === 'boolean') {
bytes += 4;
} else if (typeof value === 'string') {
bytes += value.length * 2;
} else if (typeof value === 'number') {
bytes += 8;
} else if (typeof value === 'object' && objectList.indexOf(value) === -1) {
objectList.push(value);
for (const i in value) {
if (value[i]) {
stack.push(value[i]);
}
}
}
}
return bytes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment