for vs iterators vs generators

JavaScript performance comparison

Test case created by Andy Wingo

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function integers_from(n) {
      function next() {
        return this.n++;
      }
      return { n: n, next: next };
    }
   
    function StopIteration() {}
    function isStopIteration(x) { return x === StopIteration; }
   
    function take_n(iter, max) {
      function next() {
        if (this.n++ < max)
          return iter.next();
        else
          throw StopIteration;
      }
      return { n: 0, next: next };
    }
   
    function fold(f, iter, seed) {
      try {
        while (1)
          seed = f(iter.next(), seed);
      } catch (e) {
        if (isStopIteration (e))
          return seed;
        else
          throw e;
      }
    }
   
    function dart_integers_from(n) {
      function moveNext() {
        this.current++;
        return true;
      }
      return { current: n-1, moveNext: moveNext };
    }
   
    function dart_take_n(iter, max) {
      function moveNext() {
        if (this.n++ < max && iter.moveNext()) {
          this.current = iter.current;
          return true;
        }
        else
          return false;
      }
      return {
        n: 0,
        current: undefined,
        moveNext: moveNext
      };
    }
   
    function dart_fold(f, iter, seed) {
      while (iter.moveNext())
        seed = f(iter.current, seed);
    }
   
    function sum(a, b) { return a + b; }
   
    var _ = 0;
    var ITERATIONS = 10000000
};
</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
loop sum
var sum = 0;
for (var i = 0; i < ITERATIONS; i++)
  sum += i;
_ = sum;
pending…
fold sum with iterators
_ = fold(sum, take_n(integers_from(0), ITERATIONS), 0);
 
pending…
dart fold sum with iterators
_ = dart_fold(sum, dart_take_n(dart_integers_from(0), ITERATIONS), 0);
 
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