Skip to content

Commit

Permalink
added keys-vs-values.js
Browse files Browse the repository at this point in the history
  • Loading branch information
bahmutov committed Dec 2, 2014
1 parent e47aa82 commit cbbe4d4
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
60 changes: 60 additions & 0 deletions keys-vs-values.js
Original file line number Diff line number Diff line change
@@ -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(<array of objects>);');
}(this));

0 comments on commit cbbe4d4

Please sign in to comment.