faster-string-repeat

JavaScript performance comparison

Revision 5 of this test case created by abozhilov

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(str, times) {
        times = times * str.length;
   
        var s = str;
   
        while(s.length <= times / 2) {
                s += s;
        }
   
        return s + s.slice(0, times - s.length);
    }
   
    function repeat5(str, times) {
        if (times <= 0)
            return '';
        if (times == 1)
            return str;
        if (memo[times])
            return memo[times];
        return memo[times] = repeat5(str, Math.floor(times / 2)) + repeat5(str, Math.ceil(times / 2));
    }
};
</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…
Suggested by @Prinzhorn
repeat4('a', 100).length == 100;
pending…
Dynamic programming repeat
var memo = {};
repeat5('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:

0 comments

Add a comment