Function Composition

JavaScript performance comparison

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 comp1 = compose1(fnA, fnB, fnC);
  var comp2 = compose2(fnA, fnB, fnC);
  var compR = composeR(fnA, fnB, fnC);

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
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…

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.

0 Comments