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

JavaScript performance comparison

Revision 3 of this test case created by Nick

Info

Comparison of different methods of looping through nodelists

Preparation code

<div></div>
<script>
  var nodes = document.getElementsByTagName("DIV");
  var x;
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></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…
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…
jQuery each()
$(nodes).each(function(val) {
    x = val;
});
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