for-in versus for (0...Object.keys().length) (v28)

Revision 28 of this benchmark created on


Description

Testing if the perf hit for for (0...Object.keys(..)) is enough to matter as compared to for-in.

Preparation HTML

<script>
// pre-ES5 polyfill for Object.keys()
Object.keys = Object.keys || function(o, k, r) {
  r = [];
  for (k in o)
    r.hasOwnProperty.call(o,k) && r.push(k);
  return r;
}

function iterate1() {
  var ret = "";
  for (var i in obj) {
    ret += obj[i];
  }
  return ret;
}

function iterate2() {
  var ret = "";
  var keys = Object.keys(obj);

  for (var i = 0, len = keys.length; i < len; i++) {
    ret += obj[keys[i]];
  }
}

// object with 10 keys in it
var obj = {
  a: "a",
  b: "b",
  c: "c",
  d: "d",
  e: "e",
  f: "f",
  g: "g",
  h: "h",
  i: "i",
  j: "j"
};

var tmp;
</script>

Setup

tmp = "";

Test runner

Ready to run.

Testing in
TestOps/sec
for-in
tmp += iterate1();
ready
for (0...Object.keys().length)
tmp += iterate2();
ready

Revisions

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