Last active
May 1, 2020 14:01
-
-
Save pgpbpadilla/10344038 to your computer and use it in GitHub Desktop.
Javascript `sizeof`: Calculates the memory used by an object.
This file contains 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
/*jslint indent:2, browser: true, node: true*/ | |
/** Taken from: http://stackoverflow.com/a/11900218/400544 */ | |
'use strict'; | |
(function () { | |
var typeOfWindow = typeof window; | |
function sizeof(object) { | |
var objectList = [], | |
stack = [ object ], | |
bytes = 0, | |
value, | |
i; | |
while (stack.length) { | |
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 (i in value) { | |
if (value.hasOwnProperty(i)) { | |
stack.push(value[i]); | |
} | |
} | |
} | |
} | |
return bytes; | |
} | |
// export function | |
if ('undefined' !== typeOfWindow) { // export to window | |
window.sizeof = sizeof; | |
} else { // export to node | |
module.exports = sizeof; | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment