NodeList To Array

JavaScript performance comparison

Revision 32 of this test case created

Info

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

Preparation code

<style>noder{display:none;}</style>
<script>
for(var i=10000;i--;document.body.appendChild(document.createElement('nod')));

var nl = document.getElementsByTagName('nod');
var Slice = Array.prototype.slice;
var Push = Array.prototype.push;
</script>
<script>
Benchmark.prototype.teardown = function() {
    if(arr){
    if(arr.length != nl.length){
    console.log('fail');
    }
    }
};
</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(nl);
pending…
push
var arr = [];
for (var i = 0, n; n = nl[i]; ++i) arr.push(n);
pending…
single for
var arr = []; // Will hold the array of Node's
for (var i = 0, l = nl.length; i != l; arr.push(nl[i++]));
pending…
set length first
var arr = [];
for (var i = 0, ref = arr.length = nl.length; i < ref; i++) {
 arr[i] = nl[i];
}
pending…
set length first 2
var arr = [],
  len = nl.length,
  i;

for (i = 0; i < len; i += 1) {
 arr[i] = nl[i];
}
pending…
Terse While new Array
var arr=[],len=(arr.length=nl.length),i=-1;
while(++i<len){arr[i]=nl[i]};
pending…
While Attempt Access
var i=-1,arr=[],t;
while(t=nl[++i]){arr.push(t)};
pending…
True Single For (With Temp Assignment)
for(var i=-1,arr=[],t;t=nl[++i];arr.push(t));
pending…
Cache Everything (Overload For)
var arr=[],i=-1,tmp;
for(;tmp=nl[++i];){arr.push(tmp);};
pending…
Cache Everything (Normal)
var arr=[],i=0,len=nl.length;
for(;i<len;++i){arr.push(nl[i]);};
pending…
True Single For (With Length)
for(var i=-1,arr=[],l=nl.length;i<l;arr.push(nl[++i]));
pending…
Cached Array.prototype.slice call
var arr = Slice.call(nl);
pending…
While Cached Length
var i=-1,len=nl.length,arr=[];
while(++i<len){arr.push(nl[i])};
pending…
Apply Push
var arr = []; Array.prototype.push.apply( arr , nl );
pending…
Apply Cached Push
var arr = []; Push.apply( arr , nl );
pending…
Bitwise operation
var arr = [];
for (var i=0, l=nl.length >>> 0; i++ !==l; arr[i] = nl[i]);
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