NodeList To Array

JavaScript performance comparison

Revision 52 of this test case created by shimscharf

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 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;
   
      }
    var cachedProtoPush = Array.prototype.push;
    var cachedProtoSlice = Array.prototype.slice;
};
</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
var arr = toArrayEmpty(nodes);
pending…
For Loop, Existing Array
var arr = toArrayReverseForLoop(nodes, existingArr);
pending…
Push Loop, Empty Array
var arr = toArrayPush(nodes);
pending…
Push Loop, Existing array
var arr = toArrayPush(nodes, existingArr);
pending…
Cached Push, Empty Array
var arr = cachedProtoPush.apply([], nodes);
pending…
Cached Push, Existing Array
var arr = cachedProtoPush.apply(existingArr, nodes);
pending…
Cached Slice, Empty Array
var arr = cachedProtoSlice.apply(emptyArr, 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