Last active
January 24, 2017 10:12
-
-
Save Tom910/15f1126d7ea7d5ae3c630d314d97393d to your computer and use it in GitHub Desktop.
Object-keys-vs-for-in
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
var Benchmark = require('benchmark'); | |
var suite = new Benchmark.Suite; | |
var testObject = {}; | |
for (var s = 0; s < 1000; s++) { | |
testObject[s] = Math.floor(Math.random() * 10000); | |
} | |
console.log('Testing iteration of object') | |
suite | |
.add('Object key and forEach', () => objectKeysForEach(testObject)) | |
.add('Object key and for', () => objectKeysFor(testObject)) | |
.add('Object key and for in', () => objectKeysForIn(testObject)) | |
.add('Object key and for in 2', () => objectKeysForIn(testObject)) | |
.on('cycle', event => console.log(String(event.target))) | |
.on('complete', function() {console.log('Fastest is ' + this.filter('fastest').map('name'))}) | |
.run({ 'async': true }); | |
function objectKeysForEach(obj) { | |
var result = {}; | |
Object.keys(obj).forEach(key => { | |
result[key] = obj[key] * 2; | |
}); | |
return result; | |
} | |
function objectKeysFor(obj) { | |
var result = {}; | |
var keys = Object.keys(obj); | |
for (var i = 0; i < keys.length; i++) { | |
var key = keys[i]; | |
result[key] = obj[key] * 2; | |
} | |
return result; | |
} | |
function objectKeysForIn(object) { | |
var result = {}; | |
for (var key in object) { | |
if (object.hasOwnProperty(key)) { | |
result[key] = object[key] * 2; | |
} | |
} | |
return result; | |
} | |
function objectKeysForInS(object) { | |
var result = {}; | |
for (var key in object) { | |
result[key] = object[key] * 2; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment