NodeList To Array

JavaScript performance comparison

Revision 17 of this test case created

Info

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

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><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');
};
</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
Array.prototype.slice.call
var arr = Array.prototype.slice.call(nodeList);
pending…
push
var arr = [];
for (var i = 0, n; n = nodeList[i]; ++i) arr.push(n);
pending…
single for
var l = []; // Will hold the array of Node's
for (var i = 0, ll = nodeList.length; i != ll; l.push(nodeList[i++]));
pending…
count back
var arr = [];
for (var i = nodeList.length; i--; arr.unshift(nodeList[i]));
pending…
set length first
var arr = [];
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
var a=[], l=nodeList.length>>0;
for( ; l--; a[l]=nodeList[l] );
pending…
Terse While
var a=[], l=nodeList.length>>0;
while(l--){a[l]=nodeList[l]};
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