for-in vs Object.keys forEach without inherited properties

Benchmark created on


Setup

var sampleData = document;

function forin() {
  var result = [];
  for (const key in sampleData) {
    if (Object.prototype.hasOwnProperty.call(sampleData, key)) {
      result.push(sampleData[key]);
    }
  }
  return result.length;
}

function objectKeys() {
  var result = [];
  Object.keys(sampleData).forEach(key => {
    if (Object.prototype.hasOwnProperty.call(sampleData, key)) {
      result.push(sampleData[key]);
    }
  });
  return result.length;
}

function forLoop() {
  var result = [];
  for (var i = 0, keys = Object.keys(sampleData); i < keys.length; i++) {
    result.push(sampleData[keys[i]]);
  }
  return result.length;
}

Test runner

Ready to run.

Testing in
TestOps/sec
For...in
forin();
ready
Object.keys + forEach
objectKeys();
ready
forLoop
forLoop();
ready

Revisions

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