NodeList To Array

JavaScript performance comparison

Revision 54 of this test case created by ken

Info

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

Preparation code

<div><p><a></a></p></div>
<div>
<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>
</ul>
</div>
<div>
<p><b></b></p>
<p><b></b></p>
</div>
<div>
<ul>
                <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>
</div>
<script>
Benchmark.prototype.setup = function() {
    var nodes = document.getElementsByTagName('li');
    var emptyArr = [],
        existingArr = ['hello', 'world', 'how', 'are', 'you']
   
    function toArrayPush(obj, arr) {
        arr = arr || [];
        for (var i = 0, len = obj.length; i < len; i++) {
            arr.push(obj[i])
        }
        return arr;
    }
   
    function toArrayCtor(arr) {
        return Array.apply(arr);
    }
    var cachedArrayCtor = Array.apply.bind(Array);
   
    var cachedProtoPush = Array.prototype.push;
};
</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
Push Loop, Empty Array
var arr = toArrayPush(nodes);
pending…
Cached Push, Empty Array
var arr = cachedProtoPush.apply([], nodes);
pending…
Array Constructor
var arr = toArrayCtor(nodes);
pending…
Cached Array Constructor
var arr = cachedArrayCtor(nodes);
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