Using Array.prototype.forEach on NodeList

JavaScript performance comparison

Revision 2 of this test case created by rektide

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var array = [];
    var arrayProto= Array.prototype;
    var forEach= function(a){
     
    }
    for(var i=0; i<500; i++) {
      array[i] = {className: "my-own-span"};
      var el = document.createElement("span");
      el.className = "my-own-span";
      document.body.appendChild(el);
    }
    var nodeList = document.querySelectorAll("span.my-own-span");
};

Benchmark.prototype.teardown = function() {
    for(var i=0; i<500; i++) {
      nodeList[i].parentNode.removeChild(nodeList[i]);
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
array.forEach(...)
var totalLength = 0;
array.forEach(function(x) {
  totalLength += x.className.length;
});
pending…
for loop on array
var totalLength = 0;
for(var i=0; i<array.length; i++) {
  totalLength += array[i].className.length;
}
pending…
arrayProto.forEach.call(array, ...)
var totalLength = 0;
arrayProto.forEach.call(array, function(x) {
  totalLength += x.className.length;
});
pending…
[].forEach.call(nodeList, ...)
var totalLength = 0;
[].forEach.call(nodeList, function(x) {
  totalLength += x.className.length;
});
pending…
for loop on nodeList
var totalLength = 0;
for(var i=0; i<nodeList.length; i++) {
  totalLength += nodeList[i].className.length;
}
pending…
arrayProto.forEach.call(nodeList, ...)
var totalLength = 0;
arrayProto.forEach.call(nodeList, function(x) {
  totalLength += x.className.length;
});
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