Tail call optimization (v7)

Revision 7 of this benchmark created by L8D on


Description

See https://gist.github.com/1697037.

Preparation HTML

<script src="https://rawgit.com/bfontaine/tp.js/dad7cb0f5398b1afcbc481f87c0b59c7131a49ed/tp.min.js"></script>
<script>
function tco(f) {
  var active = false, value, accumulated, args
  return function accumulator() {
    accumulated = arguments
    if (!active) {
      active = true
      while (accumulated) {
        args = accumulated
        accumulated = null
        value = f.apply(this, args)
      }
      active = false
      return value
    }
  }
}

function tra(f) {
    return function () {
        var res = f.apply(this, arguments);

        while (res.next != null) {
            res = f.apply(null, res.next);
        }

        return res.result;
    };
}

function nonRecursiveSum(x, y) {
  var args, queue = [{ 'x': x, 'y': y }];
  do {
    args = queue.pop();
    x = args.x;
    y = args.y;
    if (y > 0) {
      queue.push({ 'x': x + 1, 'y': y - 1 });
    } else if (y < 0) {
      queue.push({ 'x': x - 1, 'y': y + 1 });
    } else {
      return x;
    }
  } while (true);
}

var sumtco = tco(function(x, y) {
  return y > 0 ? sumtco(x + 1, y - 1) :
         y < 0 ? sumtco(x - 1, y + 1) :
         x
});

var sumtra = tra(function(x, y) {
  return y > 0 ? {next: [x + 1, y - 1]} :
         y < 0 ? {next: [x - 1, y + 1]} :
         {result: x}
});

var sumtp = tp(function(recur) {
  return function(x, y) {
    return y > 0 ? recur(x + 1, y - 1) :
           y < 0 ? recur(x - 1, y + 1) :
           x
  };
});
</script>

Teardown


    if (res !== 1020) throw new Error();
  

Test runner

Ready to run.

Testing in
TestOps/sec
tcp
var res = sumtco(20, 1000);
ready
nrs
var res = nonRecursiveSum(20, 1000);
ready
tra
var res = sumtra(20, 1000);
ready
sumtp
var res = sumtp(20, 1000);
ready

Revisions

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

  • Revision 1: published by John-David Dalton on
  • Revision 3: published by JeanHuguesRobert on
  • Revision 4: published by JeanHuguesRobert on
  • Revision 5: published by Paul Grenier on
  • Revision 6: published by Virasak Dungsrikaew on
  • Revision 7: published by L8D on
  • Revision 8: published on
  • Revision 9: published by Ingvar Stepanyan on
  • Revision 10: published by Ingvar Stepanyan on
  • Revision 11: published by Ingvar Stepanyan on
  • Revision 12: published by CM on
  • Revision 13: published by CM on
  • Revision 14: published by Ingvar Stepanyan on
  • Revision 15: published by Ingvar Stepanyan on
  • Revision 16: published by Ingvar Stepanyan on
  • Revision 17: published by Ingvar Stepanyan on