Object.keys vs for in for values

JavaScript performance comparison

Revision 26 of this test case created

Info

Modified by CB

Preparation code

<script>

</script>
<script>
Benchmark.prototype.setup = function() {
    var keys = Object.keys;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var getProps = Object.getOwnPropertyNames;
   
    var obj = {
      'prop1': 'value1',
      'prop2': 'value2',
      'prop3': 'value3',
      'prop4': 'value4',
      'prop5': 'value5',
      'prop6': 'value6',
      'prop7': 'value7',
      'prop8': 'value8',
      'prop9': 'value9',
      'prop10': 'value10'
    };
    if (typeof Object.setPrototypeOf === 'function') {
      Object.setPrototypeof(obj, null);
    } else {
      obj.__proto__ = null;
    }
    // mapper for Test 9
    var test9mapper = function(key) {
      return this[key];
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Object.keys
var props = keys(obj),
  index = -1,
  length = props.length,
  values = [];

while (++index < length) {
  values.push(obj[props[index]]);
}
pending…
Object.keys w/ forEach()
var values = [];
keys(obj).forEach(function(v, k, a) {
  values.push(obj[v]);
});
pending…
for-in w/ hasOwnProperty
var values = [];
for (var prop in obj) {
  hasOwnProperty.call(obj, prop) && values.push(obj[prop]);
}
pending…
Object.getOwnProperties
var props = getProps(obj),
  i = props.length,
  values = [];

while (--i >= 0) {
  values.push(obj[props[i]]);
}
pending…
`Object.keys´ /w for...loop
var props = keys(obj),
  values = [];

for (var i = 0, l = props.length; i < l; i++) {
  values.push(obj[props[i]]);
}
pending…
for (y in obj)
var q = [y
  for (y in obj)
]
pending…
for each ( y in obj )
var q = [y
  for each(y in obj)
];
pending…
Object.keys.map
var values = keys(obj).map(function(key) {
  return this[key];
}, obj);
pending…
Object.keys.map with prepared mapper
var values = keys(obj).map(test9mapper, obj);
pending…
Object.keys.map with ECMAScript6 Arrow Function
var values = keys(obj).map(key => obj[key]);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment