Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
if (typeof console === 'undefined') console = {log:print};
function forIn(o) {
let result = 0;
for (const key in o) {
if (Object.prototype.hasOwnProperty.call(o, key)) {
result += key.length + o[key].length;
}
}
return result;
}
function objectKeys(o) {
let result = 0;
for (const key of Object.keys(o)) {
result += key.length + o[key].length;
}
return result;
}
function objectKeysAndValues(o) {
let result = 0;
const keys = Object.keys(o);
const values = Object.values(o);
for (let i = 0; i < keys.length; ++i) {
result += keys[i].length + values[i].length;
}
return result;
}
function objectEntries(o) {
let result = 0;
for (const [key, val] of Object.entries(o)) {
result += key.length + val.length;
}
return result;
}
var TESTS = [
forIn,
objectKeys,
objectKeysAndValues,
objectEntries
];
var n = 1e6;
var OBJECTS = [
{},
{a:'', b:'', c:'', d:''},
{a:'', b:'', c:'', d:'', e:'', f:'', g:''},
{a:'', b:'', c:'', d:'', e:'', f:'', g:'', h:'', i:'', j:'', k:'', l:''}
];
function test(fn) {
for (var i = 0; i < n; ++i) {
let result = 0;
for (const o of OBJECTS) {
result += fn(o);
}
if (result !== 23) throw new Error(`Invalid result ${result}`);
}
}
for (var j = 0; j < TESTS.length; ++j) {
test(TESTS[j]);
}
for (var j = 0; j < TESTS.length; ++j) {
var startTime = Date.now();
test(TESTS[j]);
console.log(TESTS[j].name + ':', (Date.now() - startTime), 'ms.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment