Forked from shamasis/benchmark-compare-keys-vs-loop-obj-iteration.spec.js
Created
November 6, 2020 08:56
-
-
Save olehcambel/b2e427e5827347bd976c270613f2bb0c to your computer and use it in GitHub Desktop.
Benchmark Object.keys().forEach vs for..in loop
This file contains hidden or 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
require("microtime"); | |
const | |
_ = require('lodash'), | |
Benchmark = require('benchmark'), | |
suite = new Benchmark.Suite, | |
result = [], | |
seedSize = 10000, | |
seedData = Array(seedSize).fill().map(() => String(Math.round(Math.random() * seedSize))).reduce((obj, val) => { | |
obj[val] = val; | |
return obj; | |
}, {}); | |
suite | |
.add('iterating using object keys', function () { | |
let arr = []; | |
Object.keys(seedData).forEach((prop) => { | |
arr.push(seedData[prop]); | |
}) | |
}) | |
.add('iterating using guarded for-in loop', function () { | |
let arr = []; | |
for (let prop in seedData) { | |
if (seedData.hasOwnProperty(prop)) { | |
arr.push(seedData[prop]); | |
} | |
} | |
}) | |
.add('iterating using un-guarded for-in loop', function () { | |
let arr = []; | |
for (let prop in seedData) { | |
arr.push(seedData[prop]); | |
} | |
}) | |
.on('error', (event) => console.log(event.target.error)) | |
.on('cycle', (event) => { | |
console.log(String(event.target)) | |
result.push(event.target); | |
}) | |
.on('complete', function () { | |
console.log(`\nFastest is ${this.filter('fastest').map('name')}`); | |
result | |
.map((bench) => ({ name: bench.name, mean: bench.stats.mean})) | |
.sort((a, b) => a.mean > b.mean) | |
.forEach((bench, index) => { | |
console.log(` ${index+1}. ${bench.name}`); | |
}); | |
}) | |
.run({ 'async': true }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment