Repeat String - Javascript

I've tested the performance of all the proposed approaches.

Here is the fastest variant I've got.

String.prototype.repeat = function(count) {
    if (count < 1) return '';
    var result = '', pattern = this.valueOf();
    while (count > 1) {
        if (count & 1) result += pattern;
        count >>= 1, pattern += pattern;
    }
    return result + pattern;
};

Or as stand-alone function:

function repeat(pattern, count) {
    if (count < 1) return '';
    var result = '';
    while (count > 1) {
        if (count & 1) result += pattern;
        count >>= 1, pattern += pattern;
    }
    return result + pattern;
}

It is based on wnrph's algorithm. It is really fast. And the bigger the count, the faster it goes compared with the traditional new Array(count + 1).join(string) approach.

I've only changed 2 things:

  1. replaced pattern = this with pattern = this.valueOf() (clears one obvious type conversion);
  2. added if (count < 1) check from prototypejs to the top of function to exclude unnecessary actions in that case.
  3. applied optimisation from Dennis answer (5-7% speed up)

UPD

Created a little performance-testing playground here for those who interested.

variable count ~ 0 .. 100:

Performance diagram

constant count = 1024:

Performance diagram

Use it and make it even faster if you can :)


Note to new readers: This answer is old and and not terribly practical - it's just "clever" because it uses Array stuff to get String things done. When I wrote "less process" I definitely meant "less code" because, as others have noted in subsequent answers, it performs like a pig. So don't use it if speed matters to you.

I'd put this function onto the String object directly. Instead of creating an array, filling it, and joining it with an empty char, just create an array of the proper length, and join it with your desired string. Same result, less process!

String.prototype.repeat = function( num )
{
    return new Array( num + 1 ).join( this );
}

alert( "string to repeat\n".repeat( 4 ) );