fast loop: repeat, CoffeScript vs ES6

JavaScript performance comparison

Revision 2 of this test case created by tomByrer

Info

Comparing the performance of a couple of looping methods.

v2: dropped .join (too slow), added Barbarrosa's interpretation of ECMAScript 6 draft String.prototype.repeat, tweaked repeatOptimizedCoffee

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function repeatNaive(str, n) {
        var res = '', i;
        for (i = 0; i < n; i++) {
            res += str;
        }
        return res;
    }
   
    function repeatOptimized(str, n) {
        var res = '';
        for (n |= 0; n > 0; n >>>= 1, str += str) {
           if (n & 1) {
               res += str;
           }
        }
        return res;
    }
   
    function repeatOptimizedCoffee(str, n) {
      var res = '';
      while (n > 0) {
        if (n & 1) {
          res += str;
        }
        n >>>= 1;
        str += str;
      }
      return res;
    };
   
    function repeatES6(str, n) {
      var res = '';
      n = (+n > 0 ? 1 : -1) * Math.floor(Math.abs(n));
      if(isNaN(n)) n = 0;
      if(!isFinite(n) || n < 0) throw new RangeError();
      while (n > 0) {
        if (n & 1) {
          res += str;
        }
        n >>>= 1;
        str += str;
      }
      return res;
    };
   
    function repeatES6Optimized(str, n) {
      var res = '';
      n |= 0;  // cheated: force n to Int
      while (n > 0) {
        if (n & 1) {
          res += str;
        }
        n >>>= 1;
        str += str;
      }
      return res;
    };
};
</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
For-loop
repeatNaive('profile ', 73);
pending…
Optimized
repeatOptimized('profile ', 73);
pending…
Optimized CoffeeScript
repeatOptimizedCoffee('profile ', 73);
pending…
ES6
repeatES6('profile ', 73);
pending…
ES6 Optimized
repeatES6Optimized('profile ', 73);
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:

2 comments

tomByrer (revision owner) commented :

Android 4.3 was my US Sprint Note2: Optimized, CS, & ES6 Optimized all tied. Mobile Safari was my iPad4: all close but CoffeScript slightly fastest (I guess n |= 0 doesn't work as well as on my i7 Windows.

tomByrer (revision owner) commented :

"ES6" from https://github.com/Barbarrosa/OpenSpritz/blob/dev/spritz.js#L319-L333 based on the CoffeeScript above.

Add a comment