NodeList To Array (v52)

Revision 52 of this benchmark created by shimscharf on


Description

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

Preparation HTML

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

Setup

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;

Test runner

Ready to run.

Testing in
TestOps/sec
FOR Loop, Empty Array
var arr = toArrayEmpty(nodes);
ready
For Loop, Existing Array
var arr = toArrayReverseForLoop(nodes, existingArr);
ready
Push Loop, Empty Array
var arr = toArrayPush(nodes);
ready
Push Loop, Existing array
var arr = toArrayPush(nodes, existingArr);
ready
Cached Push, Empty Array
var arr = cachedProtoPush.apply([], nodes);
ready
Cached Push, Existing Array
var arr = cachedProtoPush.apply(existingArr, nodes);
ready
Cached Slice, Empty Array
var arr = cachedProtoSlice.apply(emptyArr, nodes);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.