for vs while

JavaScript performance comparison

Test case created by Pedro Rogério

Info

Test performance on loops using for and while

Preparation code

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
while
function loop($els, cb) {
  var i = $els.length;

  while (i > 0) {
    i -= 1;
    cb($els[i]);
  }
}

var $nodes = document.querySelectorAll(".box");

loop($nodes, function($node) {
  $node.classList.add('teste');
});
pending…
for
function forLoop($els, cb) {
  var i, len;
  for (i = 0, len = $els.length; i < len; i += 1) {
    cb($els[i]);
  }
}

var $nodes = document.querySelectorAll(".box");

forLoop($nodes, function($node) {
  $node.classList.add('teste');
});
pending…
while--
function loop($els, cb) {
  var i = $els.length;

  while (i--) {
    cb($els[i]);
  }
}

var $nodes = document.querySelectorAll(".box");

loop($nodes, function($node) {
  $node.classList.add('teste');
});
pending…
while++
function loopIncrement($els, cb) {
  var i = 0,
    max = $els.length;

  while (i < max) {
    cb($els[i], i);
    i += 1;
  }
}

var $nodes = document.querySelectorAll(".box");

loopIncrement($nodes, function($node) {
  $node.classList.add('teste');
});
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