faster-string-repeat

JavaScript performance comparison

Revision 7 of this test case created

Info

Test algorithms from http://coderkeen.com/javascript/faster-stringrepeat-method-with-ancient-egyptian-theory

Preparation code

<script>
Object.defineProperty(String.prototype, 'repeat', {value: function(times) {
      if (times < 0 || times === Infinity) {
        throw new RangeError();
      }
      var s = String(this);
      if (times < 1) return '';
      if (times % 2) return s.repeat(times - 1) + s;
      var half = s.repeat(times / 2);
      return half + half;
    }})
</script>
<script>
Benchmark.prototype.setup = function() {
    function repeat1(str, times) {
        var s = '';
        while (times-- > 0) {
            s += str;
        }
        return s;
    }
   
    function repeat2(str, times) {
        return Array(times + 1).join(str);
    }
   
    function repeat3(str, times) {
        var res = '';
        while (times > 0) {
            if (times % 2 == 1) {
                res += str;
            }
            str += str;
            times >>= 1;
        }
        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
Linear while
repeat1('a', 100).length == 100;
pending…
Linear Array#join
repeat2('a', 100).length == 100;
pending…
Logarithmic
repeat3('a', 100).length == 100;
pending…
es6-shim
'a'.repeat(100).length == 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. Here’s a list of current revisions for this page:

0 comments

Add a comment