Recursive Compose vs Iterative Compose

JavaScript performance comparison

Test case created by Bluefinger

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const add = n => m => n + m;
  const sub = n => m => n - m;
  
  const recursiveCompose = (...funcs) => (...args) => {
    const rest = funcs.slice();
    if (rest.length) {
      const fn = rest.pop();
      const result = fn(...args);
      return recursiveCompose(...rest)(result);
    }
    return args[0];
  };
  
  const recursiveCachedCompose = function (...funcs) {
    let pointer = funcs.length;
    return function composeExec(...args) {
      if (pointer--) {
        const fn = funcs[pointer];
        const result = fn(...args);
        return composeExec(result);
      }
      pointer = funcs.length;
      return args[0];
    };
  };
  
  const iterativeCompose = (...funcs) => (...args) => {
    const rest = funcs.slice();
    const start = rest.pop();
    return rest
      .reduceRight((result, fn) => fn(result), start(...args));
  };
  
  const iterativeCachedCompose = (...funcs) => {
    const rest = funcs.slice();
    const start = rest.pop();
    return (...args) =>
      rest.reduceRight((result, fn) => fn(result), start(...args));
  };
  
  const recursivePipeline = recursiveCompose(add(5), add(9), sub(3));
  const recursiveCachedPipeline = recursiveCachedCompose(add(5), add(9), sub(3));
  
  const iterativePipeline = iterativeCompose(add(5), add(9), sub(3));
  const iterativeCachedPipeline = iterativeCachedCompose(add(5), add(9), sub(3));

};
</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
Recursive
recursivePipeline(10);
pending…
Iterative
iterativePipeline(10);
pending…
Recursive Cached
recursiveCachedPipeline(10);
pending…
Iterative Cached
iterativeCachedPipeline(10);
pending…

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

Compare results of other browsers

0 Comments