From cbbe4d42d874acd78996bafa65e69f93fa90abeb Mon Sep 17 00:00:00 2001 From: Gleb Bahmutov Date: Tue, 2 Dec 2014 16:27:22 -0500 Subject: [PATCH] added keys-vs-values.js --- README.md | 1 + keys-vs-values.js | 60 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 keys-vs-values.js diff --git a/README.md b/README.md index 98d5710..ab5c61e 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ from [addyosmani/timing.js](https://github.com/addyosmani/timing.js). * [local-storage-size.js](local-storage-size.js) - measures size of the strings in the `localStorage`. * [expensive-keys.js](expensive-keys.js) - measures how much space individual keys and their values take up in a collection of objects, read [Measuring Space Allocation][measure]. +* [keys-vs-values.js](keys-vs-values.js) - measures length of keys vs length of values in an array. ### Angular performance diff --git a/keys-vs-values.js b/keys-vs-values.js new file mode 100644 index 0000000..af4d343 --- /dev/null +++ b/keys-vs-values.js @@ -0,0 +1,60 @@ +// measures how much memory object keys take vs values in collection of objects +(function keysVsValuesInit(root) { + function stringSize(str) { + // JavaScript strings are unicode UTF-16 up to 2 bytes per character + return str.length * 2; + } + + function objectSize(obj) { + if (typeof obj === 'string') { + return stringSize(obj); + } + return stringSize(JSON.stringify(obj)); + } + + function values(obj) { + return Object.keys(obj).map(function (key) { + return obj[key]; + }); + } + + function listSize(values) { + return values.reduce(function (total, value) { + return objectSize(value) + total; + }, 0); + } + + function keysValues(obj) { + if (typeof obj === 'object') { + return { + keys: stringSize( Object.keys(obj).join('') ), + values: listSize( values(obj) ) + }; + } else { + return { + keys: 0, + values: objectSize(obj) + }; + } + } + + function keysVsValues(items) { + if (!Array.isArray(items) && typeof items === 'object') { + return keysVsValues([items]); + } + + console.assert(Array.isArray(items)); + return items.reduce(function (sizes, item) { + var size = keysValues(item); + sizes.keys += size.keys; + sizes.values += size.values; + return sizes; + }, { + keys: 0, + values: 0 + }); + } + + root.keysVsValues = keysVsValues; + console.log('try keysVsValues();'); +}(this));