original forEach with scope chain searching VS while loop without that

JavaScript performance comparison

Test case created by kerryChen95

Info

original forEach with scope chain searching VS while loop without that

Preparation code

<script>
function initArrByWhileLoop (len) {
  // create a dense array
  var arr = Array.apply(null, new Array(len));
  var i = 0;
  // only this part is different:
  // there is no identifier needed searching through scope chain
  while (i < len) {
    arr[i++] = i;
  }
  return arr;
}

function initArrByForEachMethod (len) {
  // create a dense array
  var arr = Array.apply(null, new Array(len));
  var i = 0;
  // only this part is different:
  // there are two identifier needed searching through scope chain
  arr.forEach(function () {
    arr[i++] = i;
  });
  return arr;
}

var length = 10000;
initArrByWhileLoop(length).length === length || alert('initArrByWhileLoop broken');
initArrByForEachMethod(length).length === length || alert('initArrByForEachMethod broken');
</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
initArrByWhileLoop
initArrByWhileLoop(length);
pending…
initArrByForEachMethod
initArrByForEachMethod(length)
pending…

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

Compare results of other browsers

0 comments

Add a comment