JavaScript String Repetition Algorithm

JavaScript performance comparison

Revision 4 of this test case created

Info

Test cases for string repetition. http://stackoverflow.com/questions/202605/repeat-string-javascript/17800645#17800645

Preparation code

<script src="//myjs.us/param.js"></script>
A string of the indicated string length will be replicated.
<script>
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;
    }
   
    tLengths = [10000];
    tStrings = [];
    for (i=0; i<tLengths.length; i++)
    tStrings[i] = stringFill3('a', tLengths[i]);
    queryParams = param();
    testCase = parseInt(queryParams['test-case']);
    if (testCase > tLengths.length || testCase < 1)
    testCase = 7;
    stringLength = tLengths[testCase];
    stringValue = tStrings[testCase];
    stringRepeats = 100;
    alert('Test case ' + testCase + ': string length = ' + stringLength);
   
    function repeat(x, num )
    {
        return new Array( num + 1 ).join( x);
    }
    function repeat2(x, count) {
        if (count < 1) return '';
        var result = '', pattern = x.valueOf();
        while (count > 0) {
            if (count & 1) result += pattern;
            count >>= 1, pattern += pattern;
        }
        return result;
    };
    stringValue = 'a';
    stringRepeats = 80000;
   
};
</script>

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);
pending…
Accepted Answer on Stack Overflow
repeat(stringValue, stringRepeats);
pending…
A degraded version of my solution
repeat2(stringValue, stringRepeats);
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