partial application via apply,closures and/or bind (v2)

Revision 2 of this benchmark created by hiasltiasl on


Setup

var Functions = Function.prototype;
    var Arrays = Array.prototype;
    var shift = Functions.call.bind(Arrays.shift);
    var slice= Functions.call.bind(Arrays.slice);
    var unshift = Functions.call.bind(Arrays.unshift);
    var unshiftAll = Functions.apply.bind(Arrays.unshift);
    
    
    function sum() {
      var res = 0;
      for (var i = 0, ii = arguments.length; i < ii; i++)
        res += arguments[i];
      return res;
    }
    
    function partialApply() {
      var f = shift(arguments);
      var boundArgs = arguments;
      return function() {
        unshiftAll(arguments, boundArgs);
        return f.apply(this, arguments);
      };
    }
    
    function partialDirect(f, arg1, arg2) {
      return function(arg3, arg4) {
        return f(arg1, arg2, arg3, arg4);
      };
    }
    
    function partialBindApply(f, arg1, arg2) {
      return function() {
        return f.bind(this, arg1, arg2).apply(this, arguments);
      };
    }
    
    function partialApplyBind(f) {
      var boundArgs = slice(arguments);
      return function() {
        boundArgs[0] = this;
        return f.bind.apply(f, boundArgs).apply(this, arguments);
      };
    }
    
    var boundBind = sum.bind(this, 1, 2);
    var boundApply = partialApply(sum, 1, 2);
    var boundDirect = partialDirect(sum, 1, 2);
    var boundBindApply = partialBindApply(sum, 1, 2);
    var boundApplyBind = partialApply(sum, 1, 2);
    var boundClosureApply = function () {
      unshift(arguments, 1, 2);
      return sum.apply(this, arguments);
    };
    var boundClosureDirect = function (arg3, arg4) {
      return sum(1, 2, arg3, arg4);
    };

Test runner

Ready to run.

Testing in
TestOps/sec
partial apply
boundApply(3, 4);
ready
partial direct
boundDirect(3, 4);
ready
bind
boundBind(3, 4);
ready
partial apply bind
boundApplyBind(3, 4);
ready
partial bind apply
boundBindApply(3, 4);
ready
closure apply
boundClosureApply(3, 4);
ready
closure direct
boundClosureDirect(3, 4);
ready

Revisions

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

  • Revision 2: published by hiasltiasl on