Nodelist to Array

JavaScript performance comparison

Revision 7 of this test case created by shimscharf


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

Preparation code

                <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>
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;

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
For Loop, Existing Array
toArrayReverseForLoop (nodes, existingArr);
push, empty array
toArrayPush (nodes);
Push, Existing array
toArrayPush (nodes, existingArr);

Compare results of other browsers


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:


Comment form temporarily disabled.

Add a comment