Iterating over object properties (v20)

Revision 20 of this benchmark created by Larry Gordon on


Description

Comparing various approaches to iterating over an object's enumerable properties.

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.js"></script>

Setup

var testData = {};
    var fixture = '';
    var i;
    var dataKeys;
    var dataLen;
    for (i = 0; i < 100; ++i) {
      testData['user' + i] = 'user' + i;
    }
    dataKeys = Object.keys(testData);
    dataLen = dataKeys.length;
    for (i = 0; i < dataLen; i++) {
      fixture += testData[dataKeys[i]];
    }

Test runner

Ready to run.

Testing in
TestOps/sec
for…in
var result = '';
for (var property in testData) {
  if (testData.hasOwnProperty(property)) {
    result += testData[property];
  }
}
if (result !== fixture) console.log("whoa?");
ready
for loop Object.keys no cache length
var result = '';
for (var i = 0, keys = Object.keys(testData); i < keys.length;i++) {
  result += testData[keys[i]];
}
if (result !== fixture) console.log("whoa?");
ready
for loop Object.keys w/cache length
var result = '';
for (var i = 0, keys = Object.keys(testData), l = keys.length; i < l;i++) {
  result += testData[keys[i]];
}
if (result !== fixture) console.log("whoa?");
ready
Object.keys + forEach
var result = '';
Object.keys(testData).forEach(function(key) {
  result += testData[key];
});
if (result !== fixture) console.log("whoa?");
ready
_.each
var result = '';
_.each(testData, function(value) {
  result += value;
});
if (result !== fixture) console.log("whoa?");
ready
for loop _.keys w/cache length
var result = '';
for (var i = 0, keys = _.keys(testData), l = keys.length; i < l; ++i) {
  result += testData[keys[i]];
}
if (result !== fixture) console.log("whoa?");
ready
jQuery.each
var result = '';
$.each(testData, function(key, value) {
  result += value;
});
if (result !== fixture) console.log("whoa?");
ready
Object.keys forEach + cached callback
var result = '';
var cached = function cached(key) {
  result = testData[key];
};
Object.keys(testData).forEach(cached);
if (result !== fixture) console.log("whoa?");
ready
while loop Object.keys reverse
var result = '';
var keys = Object.keys(testData);
var len = keys.length;
while (len--) {
  result += testData[keys[len]];
}
if (result !== fixture) console.log("whoa?");
ready
while loop Object.keys forward
var result = '';
var keys = Object.keys(testData);
var len = keys.length;
var total = len - 1;
while (len--) {
    result += testData[keys[total - len]];
}
if (result !== fixture) console.log("whoa?");
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.