NodeList To Array

JavaScript performance comparison

Revision 20 of this test case created

Info

http://stackoverflow.com/questions/3199588/fastest-way-to-convert-javascript-nodelist-to-array

Preparation code

<h1 id="resultChecker" style="background:green;position:fixed;right:0;top:0;color:white;">Nothing Yet</h1>
<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><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><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><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<script>
Benchmark.prototype.setup = function() {
    var nodeList = document.querySelectorAll('div');
    var item;
    var arr = [];
};

Benchmark.prototype.teardown = function() {
    document.getElementById('resultChecker').textContent = arr.length;
    arr = [];
    nodeList = document.querySelectorAll('div');
};
</script>

Preparation code output

Nothing Yet

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.prototype.slice.call
arr = Array.prototype.slice.call(nodeList);
pending…
push
for (var i = 0, n; n = nodeList[i]; ++i) arr.push(n);
pending…
single for
for (var i = 0, len = nodeList.length; i != len; arr.push(nodeList[len++]));
pending…
count back
for (var i = nodeList.length; i--; arr.unshift(nodeList[i]));
pending…
set length first
for (var i = 0, ref = arr.length = nodeList.length; i < ref; i++) {
  arr[i] = nodeList[i];
}
pending…
set length first with Array constructor
var ref = nodeList.length,
    arr = new Array(ref);
for (var i = 0; i < ref; i++) {
  arr[i] = nodeList[i];
}
pending…
Set Length First, Terse
for(var i = nodeList.length>>0; i--; arr[i]=nodeList[i] );
pending…
Terse While
i=nodeList.length>>0;
while(i--){arr[i]=nodeList[i]};
pending…
while(item = Array.prototype.shift(nodeList)){
arr.push(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