Recursion Comparison

JavaScript performance comparison

Revision 2 of this test case created by David Atchley

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  "use strict";
  
  function trampoline(fn){
      return function(/*args*/){
          var res = fn.apply(this, arguments);
          while(res instanceof Function){
              res = res();
          }
          return res;
      }
  }
  // Generate an array of numbers in a given range.
  // Tail Recursive implementation
  function _rangetr(s, e, res) {
    res = res || [];
    res.push(s);
    return s == e ? res : function() { return _rangetr(s<e ? ++s : --s, e, res); };
  }
  
  // Generate an array of numbers in a given range.
  // Tail Recursive implementation
  function rangetr(s, e, res) {
    res = res || [];
    res.push(s);
    return s == e ? res : rangetr(s<e ? ++s : --s, e, res);
  }
  
  // Generate an array of numbers in a given range.
  // Recursive implementation
  function ranger(s, e) {
    var res = [];
    
    res.push(s);
    return s == e ? res : res.concat(ranger(s<e ? ++s : --s, e));
  }
  
  // Generate an array of numbers in a given range.
  // Iterative implementation
  function range(s, e) {
      var res = [];
  
      while (s != e) {
          res.push(s);
          s < e ? s++ : s--;
      }
      res.push(s); 
      return res;
  }
  
  // Babel transpiled tail-call optimization
  function rangetr_babel(_x, _x2, _x3) {
    var _again = true;
  
    _function: while (_again) {
      var s = _x,
          e = _x2,
          res = _x3;
      _again = false;
  
      res = res || [];
      res.push(s);
      if (s == e) {
        return res;
      } else {
        _x = s < e ? ++s : --s;
        _x2 = e;
        _x3 = res;
        _again = true;
        continue _function;
      }
    }
  }

};
</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
Iteration
range(1,100);
pending…
Recursion
ranger(1,100)
pending…
Tail Recursive
rangetr(1,100);
pending…
Tail Recursive w/ Trampoline
trampoline(_rangetr)(1,100)
pending…
Babel Tail Call Optimized
rangetr_babel(1,100);
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