arguments to array (v29)

Revision 29 of this benchmark created by espretto on


Description

what's the fastest way to convert an arguments instance to an array? Also, certain patterns prevent V8 from optimizing the complete function in nodejs as pointed out here. only accessing arguments via index or passing to apply are valid methods.

Setup

// shortcuts for fairness
    // ----------------------
    var arrayPush = Array.prototype.push,
        arrayConcat = Array.prototype.concat,
        objectToString = Object.prototype.toString;
    
    (function(){
      Object.defineProperty(arguments.constructor.prototype, 'slice', {
        value: Array.prototype.slice
      });
    }());
    
    // competitors
    // -----------
    
    function pushApply(){
      var args = []; // js is lisp
      return arrayPush.apply(args, arguments), args;
    }
    
    function loopAssign(){
      for(var i = arguments.length, args = new Array(i); i--;) args[i] = arguments[i];
      return args;
    }
    
    function loopPush(){
      for(var i = arguments.length, args = []; i--;) args.push(arguments[i]);
      return args;
    }
    
    function loopPushShort(){
      var len = arguments.length,
          i = 0,
          args = [];
      while (args.push(arguments[i++]) !== len) {}
      return args;
    }
    
    function arrayOf(){
      return (Array.of || loopPush).apply(null, arguments);
    }
    
    function arrayApply(){
      return Array.apply(null, arguments);
    }
    
    function argumentsSlice(){
      return arguments.slice();
    }
    
    // test function
    // -------------
    function test(fn){
      var i, len = i = 100,
          args = new Array(len),
          result;
    
      while(i--) args[i] = Math.random() * i;
    
      result = fn.apply(null, args);
      
      if (objectToString.call(result) !== '[object Array]' ||
          result.length !== len
      ){
        throw new Error(fn.name + ' failed the test');
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
pushApply
test(pushApply)
ready
loopAssign
test(loopAssign)
ready
loopPush
test(loopPush)
ready
arrayOf
test(arrayOf)
ready
arrayApply (limited)
test(arrayApply)
ready
argumentsSlice
test(argumentsSlice)
ready
loopPushShort
test(loopPushShort);
ready

Revisions

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