Skip to content

Commit cbbe4d4

Browse files
committed
added keys-vs-values.js
1 parent e47aa82 commit cbbe4d4

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ from [addyosmani/timing.js](https://github.com/addyosmani/timing.js).
1919
* [local-storage-size.js](local-storage-size.js) - measures size of the strings in the `localStorage`.
2020
* [expensive-keys.js](expensive-keys.js) - measures how much space individual keys and their values
2121
take up in a collection of objects, read [Measuring Space Allocation][measure].
22+
* [keys-vs-values.js](keys-vs-values.js) - measures length of keys vs length of values in an array.
2223

2324
### Angular performance
2425

keys-vs-values.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// measures how much memory object keys take vs values in collection of objects
2+
(function keysVsValuesInit(root) {
3+
function stringSize(str) {
4+
// JavaScript strings are unicode UTF-16 up to 2 bytes per character
5+
return str.length * 2;
6+
}
7+
8+
function objectSize(obj) {
9+
if (typeof obj === 'string') {
10+
return stringSize(obj);
11+
}
12+
return stringSize(JSON.stringify(obj));
13+
}
14+
15+
function values(obj) {
16+
return Object.keys(obj).map(function (key) {
17+
return obj[key];
18+
});
19+
}
20+
21+
function listSize(values) {
22+
return values.reduce(function (total, value) {
23+
return objectSize(value) + total;
24+
}, 0);
25+
}
26+
27+
function keysValues(obj) {
28+
if (typeof obj === 'object') {
29+
return {
30+
keys: stringSize( Object.keys(obj).join('') ),
31+
values: listSize( values(obj) )
32+
};
33+
} else {
34+
return {
35+
keys: 0,
36+
values: objectSize(obj)
37+
};
38+
}
39+
}
40+
41+
function keysVsValues(items) {
42+
if (!Array.isArray(items) && typeof items === 'object') {
43+
return keysVsValues([items]);
44+
}
45+
46+
console.assert(Array.isArray(items));
47+
return items.reduce(function (sizes, item) {
48+
var size = keysValues(item);
49+
sizes.keys += size.keys;
50+
sizes.values += size.values;
51+
return sizes;
52+
}, {
53+
keys: 0,
54+
values: 0
55+
});
56+
}
57+
58+
root.keysVsValues = keysVsValues;
59+
console.log('try keysVsValues(<array of objects>);');
60+
}(this));

0 commit comments

Comments
 (0)