Object.keys vs for in for values

JavaScript performance comparison

Revision 71 of this test case created

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>

</script>
<script>
Benchmark.prototype.setup = function() {
    var obj_proto_keys = Object.keys;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
   
    var obj = {
    'prop1': 'value1',
    'prop2': 'value2',
    'prop3': 'value3',
    'prop4': 'value4',
    'prop5': 'value5',
    'prop6': 'value6',
    'prop7': 'value7',
    'prop8': 'value8',
    'prop9': 'value9',
    'prop10': 'value10'
    };
};
</script>

Preparation code output

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 = Object.keys(obj),
    index = -1,
    length = props.length,  // *NOTE* ! There was a bug here in the earlier revision - it used keys.length (!) instead of props.length, giving 1! /ORC
    values = [];

while (++index < length) {
  values.push(obj[props[index]]);
}
pending…
for-in w/ hasOwnProperty
var values = [], prop;
for (prop in obj) {
  if (hasOwnProperty.call(obj, prop)) {
    values.push(obj[prop]);
  }
}
pending…
for-in w/o hasOwnProperty
var values = [], prop;
for (prop in obj) {
  values.push(obj[prop]);
}
pending…
for-in w/ hasOwnProperty without call
var values = [], prop;
for (prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    values.push(obj[prop]);
  }
}
pending…
Object.keys cached as 'keys'
var props = obj_proto_keys(obj),
    index = -1,
    length = props.length,
    values = [];

while (++index < length) {
  values.push(obj[props[index]]);
}
pending…
for-in w/o hasOwnProperty and length computation
var values = [], prop;
var count = 0;
for (prop in obj) {
count++
}
for (prop in obj) {
  values.push(obj[prop]);
}
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