Apply vs Custom Apply

Benchmark created by Yaroslav on


Setup

var slice = Array.prototype.slice;
    
    function customApply(func, obj, args) {
      var arg1, arg2, arg3;
      arg1 = args[0];
      arg2 = args[1];
      arg3 = args[2];
      switch (args.length) {
        case 0:
          return func.call(obj);
        case 1:
          return func.call(obj, arg1);
        case 2:
          return func.call(obj, arg1, arg2);
        case 3:
          return func.call(obj, arg1, arg2, arg3);
        default:
          return func.apply(obj, args);
      }
    }
    
    function wrapperFuncDefaultApply() {
      return targetFunc.apply(null, slice.call(arguments, 1));
    }
    
    function wrapperFuncCustomApply() {
      return customApply(targetFunc, null, arguments, 1);
    }
    
    function targetFunc(arg1, arg2, arg3, arg4) {
      var ret = 0;
      for (var i = 0; i < 10; ++i) {
        ret += i * i;
      }
      return ret;
    }
    
    function randArgsNum() {
      return Math.floor(Math.random() * 5);
    }
    
    function randArgsOffset() {
      return Math.floor(Math.random() * 3);
    }
    var argsChunks = [
      [],
      [1],
      [1, 2],
      [1, 2, 3],
      [1, 2, 3, 4]
    ];

Test runner

Ready to run.

Testing in
TestOps/sec
Default apply
wrapperFuncDefaultApply.apply(null, argsChunks[randArgsNum()]);
ready
Custom apply
wrapperFuncCustomApply.apply(null, argsChunks[randArgsNum()]);
ready

Revisions

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

  • Revision 1: published by Yaroslav on