Created
January 15, 2018 02:53
-
-
Save brn/f7047016369a9828bee6c717ce426f4b to your computer and use it in GitHub Desktop.
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
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:''}, | |
{1:'', 2:'', 3:'', 4:'', 5:'', f:'', g:''}, | |
{[Symbol('test')]: '', a: ''}, | |
{a:'', b:'', c:'', d:'', e:'', f:'', g:'', h:'', i:'', j:'', k:'', l:''} | |
]; | |
Object.defineProperties(OBJECTS[3], { | |
'b': { | |
enumerable: false, | |
value: '' | |
}, | |
1: { | |
enumerable: true, | |
value: '' | |
} | |
}); | |
function test(fn) { | |
for (var i = 0; i < n; ++i) { | |
let result = 0; | |
for (const o of OBJECTS) { | |
result += fn(o); | |
} | |
if (result !== 25) 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