# faster-string-repeat

## JavaScript performance comparison

Revision 12 of this test case created

## Info

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

## Preparation code

`` <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;    }        function repeat4(x, n) {      /* e.g., repeat("abc", 2) === "abcabc" */      var s = '';      for (;;) {        if (n & 1) s += x;        n >>= 1;        if (n) x += x;        else break;      }      return s;    }        function repeat4a(x, n) {      /* e.g., repeat("abc", 2) === "abcabc" */      var s = '';      do {        if (n & 1) s += x;        n >>= 1;        if (n) x += x;        else break;      }      while (n);          return s;    }        function repeat4b(x, n) {      /* e.g., repeat("abc", 2) === "abcabc" */      var s = '';          while (n) {        if (n & 1) s += x;        n >>= 1;        if (n) x += x;        else break;      }          return s;    }        String.prototype.repeat_x = function(count) {      if (count < 1) return '';      var result = '',        pattern = this.valueOf();      while (count > 0) {        if (count & 1) result += pattern;        count >>= 1, pattern += pattern;      }      return result;    };            function repeat5(x, n) {          if (n > 1)        return x + '' + repeat5(x, n - 1);          if (n == 1)        return x;          if (n == 0)        return '';        }  };</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…
For speed loop
``repeat4('a', 100).length == 100;``
pending…
do-While speed loop
``repeat4a('a', 100).length == 100;``
pending…
While-do speed loop
``repeat4b('a', 100).length == 100;``
pending…
prototype repeat_x
``'a'.repeat_x(100).length == 100;``
pending…
recursion
``repeat5('a', 100).length == 100;``
pending…

## 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: