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

JavaScript performance comparison

Revision 11 of this test case created by elleestcrimi

Info

Comparison of different methods of looping through nodelists

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<script>
  var nodes = document.getElementsByTagName("DIV");
  var x;
</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
for in
for (node in nodes) {
  x = node;
}
pending…
for
var nodesLength = nodes.length;

for (var i = 0; i < nodesLength; i++) {
  x = nodes[i];
}
pending…
while
var i = 0;
var nodesLength = nodes.length;

while (i < nodesLength) {
  x = nodes[i];
  i++;
}
pending…
$.each
$.each(nodes, function(index, node) {
  x = node
});
pending…
.each
$(nodes).each(function(index, node) {
  x = node
});
pending…
.forEach
[].forEach.call(nodes, function(item) {
  x = item;
});
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