Nodelist to Array

JavaScript performance comparison

Revision 7 of this test case created by shimscharf

Info

Fastest method to convert short nodelist or other short array-like objects to an array

Preparation code

<div>
        <ul>
                <li id="item-2"><a href="#">item 1</a></li>
                <li id="item-1"><a href="#">item 2</a></li>
                <li id="item-3"><a href="#">item 3</a></li>
                <li id="item-3"><a href="#">item 4</a></li>
                <li id="item-3"><a href="#">item 5</a></li>
                <li id="item-3"><a href="#">item 6</a></li>
                <li id="item-3"><a href="#">item 7</a></li>
                <li id="item-3"><a href="#">item 8</a></li>
                <li id="item-3"><a href="#">item 9</a></li>
                <li id="item-3"><a href="#">item 10</a></li>
        </ul>
</div>
<script>
Benchmark.prototype.setup = function() {
    var nodes = document.getElementsByTagName('li');
    var    emptyArr = [],
        existingArr = ['hello', 'world', 'how', 'are', 'you']
   
    function toArrayEmpty (obj) {
         obj = (len = obj.length) ? obj : [obj];
         arr = [];
                 for(; len-- ; arr[len] = obj[len]);
                 return arr;
         
    }
   
    function toArrayReverseForLoop (obj, arr) {
         obj = obj.length ? obj : [obj];
                 var index = arr ? arr.length + obj.length : obj.length;
                 var len = obj.length; arr = arr || [];
                 for(; len-- && index-- ; arr[index] = obj[len]);
                 return arr;
    }
   
    function toArrayPush (obj, arr) {
         arr = arr || [];
         for(var i=0, len=obj.length; i<len ; i++){
              arr.push ( obj[i] )
         }
                 return arr;
   
    }
};
</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 loop, Empty Array
toArrayEmpty(nodes);
pending…
For Loop, Existing Array
toArrayReverseForLoop (nodes, existingArr);
pending…
push, empty array
toArrayPush (nodes);
pending…
Push, Existing array
toArrayPush (nodes, existingArr);
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