String.repeat() mesure

Testing performance of different variants of String.repeat() http://stackoverflow.com/questions/202605/repeat-string-javascript/5450113#5450113

by olragon

HTML

<script src="http://www.broofa.com/Tools/JSLitmus/JSLitmus.js"></script>

JavaScript

var tests = {
    
    // https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/string.js#L539
    // http://stackoverflow.com/questions/202605/repeat-string-javascript/2433358#2433358
    'new Array.join() (prototypejs)' : function(count) {
        return count < 1 ? '' : new Array(count + 1).join(this.valueOf());
    },
    
    // http://stackoverflow.com/q/202605/489553
    // optimized: this.valueOf(), while loop
    'array.push().join()' : function(count) {
        var result = [], pattern = this.valueOf(), i = count;
        while (i--) result.push(pattern);
        return result.join('');
    },
    
    // http://stackoverflow.com/questions/202605/repeat-string-javascript/202626#202626
    // optimized: this.valueOf(), while loop
    '(result += string) x count' : function(count) {
        var result = '', pattern = this.valueOf(), i = count;
        while (i--) result += pattern;
        return result;
    },
    
    // http://stackoverflow.com/questions/202605/repeat-string-javascript/4152613#4152613
    'result += growing pattern' : function(count){
        var result = '';
        var pattern = this;
        while (count > 0) {
            if (count & 1) result += pattern;
            count >>= 1;
            pattern += pattern;
        };
        return result;
    },
    
    // final: growing pattern + prototypejs check (count < 1)
    'final' : 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;
    }
    
};

// repeated string
var string = '!';
// count paremeter is changed on every test iteration, limit it's maximum value here
var maxCount = 100;

var n = 0;
$.each(tests, function(name) {
    var fn = tests[name];
    JSLitmus.test(++n + '. ' + name, function(count) {
        while (count--) { fn.call(string, count %...