JavaScript String Repetition Algorithm

JavaScript performance comparison

Revision 6 of this test case created


Test cases for string repetition.

Preparation code

<script src="//"></script>
A string of the indicated string length will be replicated.
Benchmark.prototype.setup = function() {
    function stringFill3(x, n) {
        var s = '';
        for (;;) {
            if (n & 1) s += x;
            n >>= 1;
            if (n) x += x;
            else break;
        return s;
    stringValue = 'a';
    stringRepeats = 100000;
    function repeat(x, num )
        return new Array( num + 1 ).join( x);
    function repeat2(x, count) {
        var result = '', pattern = ['', x, x=x+x];
        while (count > 0) {
            result += pattern[count&1]+pattern [count&2];
            count >>=2 , pattern[1]=x=x+x,pattern[2]=x=x+x;
        return result;
    function repeat3(x, n) { return x.repeat(n); }

Preparation code output

A string of the indicated string length will be replicated.

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Original Algorithm by Joseph Myers
stringFill3(stringValue, stringRepeats);
Accepted Answer on Stack Overflow
repeat(stringValue, stringRepeats);
A degraded version of my solution
repeat2(stringValue, stringRepeats);

Compare results of other browsers


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:


Add a comment