faster-string-repeat

JavaScript performance comparison

Revision 6 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(string, count) {
        var half;
        if (count < 1) return '';
        if (count % 2) return repeat4(string, count - 1) + string;
        half = repeat4(string, count / 2);
        return half + half;
    }
};
</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…
Exponentiation by squaring
repeat4('a', 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:

2 comments

commented :

It's neck and neck on Firefox Nightly too with "Exponentiation by squaring" coming out a few % points on top.

Add a comment