forEach() compared to for() and while()

JavaScript performance comparison

Revision 7 of this test case created by Hmm

Info

Comparison of different methods of looping through nodelists

Preparation code

<div>
  <div>
  </div>
  <div>
  </div>
  <div>
  </div>
  <div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
      <div>
      </div>
    </div>
    <div>
      <div>
        <div>
        </div>
      </div>
      <div>
      </div>
      <div>
      </div>
      <div>
        <div>
        </div>
      </div>
      <div>
      </div>
      <div>
      </div>
      <div>
      </div>
    </div>
<script>
Benchmark.prototype.setup = function() {
    var nodes = document.getElementsByTagName("DIV"),
        x = null;
};

Benchmark.prototype.teardown = function() {
    nodes = null;
};
</script>

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
[].forEach
[].forEach.call(nodes, function(item) {
  x = item;
});
pending…
for
for (var i = 0; i < nodes.length; i++) {
  x = nodes[i];
}
pending…
for backwards
for (var i = nodes.length; i--;) {
  x = nodes[i];
}
pending…
while
var i = 0;
while (i < nodes.length) {
  x = nodes[i];
  i++;
}
pending…
while backwards
var i = nodes.length;
while (i--) {
  x = nodes[i];
}
pending…
for in
for (var i in nodes) {
  x = nodes[i];
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment