.each vs. for vs recursion (v47)

Revision 47 of this benchmark created on


Preparation HTML

<script>
  var arr = [],
      loop = 5000;

  while (loop--) {
    arr[loop - 1] = loop;
  }

  var sum = 0;
  var fn = function(x) {
      sum += x;
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
forEach()
arr.forEach(fn);
ready
for
for (var i = 0; i < arr.length; i++) {
  fn(arr[i]);
}
ready
for2
for (var i = 0; i < arr.length; ++i) {
  fn(arr[i]);
}
ready
for, caching length
for (var i = 0, len = arr.length; i < len; ++i) {
  fn(arr[i]);
}
ready
assign in for
for (var i = 0, j; j = arr[i]; i++) {
  fn(j);
}
ready
while
var i = 0;
while (i < arr.length) {
  fn(arr[i]);
  i++;
}
ready
for, caching length + call
for (var i = 0, len = arr.length; i < len; i++) {
  fn.call(null, arr[i]);
}
ready
for, not setting len variable
for (var i = arr.length; i > 0;) {
  fn(arr[--i]);
}
ready
while, counting down
var i = arr.length;
while (i > 0) {
  fn(arr[--i]);
}
ready
for loop countin' down and floutin' the rules
for (var i = arr.length; i > 0; fn(arr[--i])) {}
ready
while until undefined, pop
cop = arr.slice();
while (x = cop.pop()) {
  fn(x);
}
ready
while until undefined, shift
cop = arr.slice();
while (x = cop.shift()) {
  fn(x);
}
ready
while until undefined, counting up
i = 0;
while (x = arr[i++]) {
  fn(x);
}
ready
reduce
arr.reduce(function(_, n) { fn(n) }, null);
ready
recursive, closure
function doLoop() {
  fn(arr.pop());
  if (arr.length != 0) doLoop();
}
doLoop();
ready
recursive
function doLoop(a) {
  fn(a.pop());
  if (a.length != 0) doLoop(a);
}
doLoop(arr);
ready
recursive, closure with shift
function doLoop() {
  fn(arr.shift());
  if (arr.length != 0) doLoop();
}
doLoop();
ready

Revisions

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