Function Composition

JavaScript performance comparison

Revision 2 of this test case created by Joshua T Kalis

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function fnA(a) {return a + 1;}
    function fnB(a) {return a + 3;}
    function fnC(a) {return a + 5;}
   
    var compose1 = function() {
      var funcs = arguments;
      return function() {
        var args = arguments;
        for (var i = funcs.length - 1; i >= 0; i--) {
          args = [funcs[i].apply(this, args)];
        }
        return args[0];
      };
    };
   
    var compose2 = function () {
      var comp = function (a) {return a;}
        , funcs = Array.prototype.slice.call(arguments, 0);
   
      while (funcs.length) {
        comp = (function(a, b) {
          return function() {
            return b(a.apply(this, arguments));
          };
        }(funcs.shift(), comp));
      }
   
      return comp;
    }
   
    var composeR = function () {
      var funcs = Array.prototype.slice.call(arguments, 0);
   
      function r (input, list) {
        return list.length
          ? r(list[0](input), list.slice(1))
          : input;
      }
   
      return function (i) {
        return r(i, funcs);
      }
    }
   
    var composr = function () {
      function _slice (args, indx) {
        return Array.prototype.slice.call(args, indx || 0);
      }
   
      function r (list) {
        var input = _slice(arguments, 1);
   
        return list.length
          ? r(list.slice(1), list.shift().apply(this, input))
          : input[0];
      }
   
      var funcs = _slice(arguments);
   
      return function () {
        return r.bind(this, funcs).apply(this, _slice(arguments));
      }
    }
   
    var comp1 = compose1(fnA, fnB, fnC);
    var comp2 = compose2(fnA, fnB, fnC);
    var compR = composeR(fnA, fnB, fnC);
    var compr2 = composr(fnA, fnB, fnC);
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Underscore's compose execution
var count = 10000
while (count-- && comp1(1));
pending…
my attempt
var count = 10000
while (count-- && comp2(1));
pending…
recursive attempt
var count = 10000
while (count-- && compR(1));
pending…
another
var count = 10000
while (count-- && compr2(1));
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