Repeat String - Javascript

前端 未结 30 2421
长情又很酷
长情又很酷 2020-11-22 08:46

What is the best or most concise method for returning a string repeated an arbitrary amount of times?

The following is my best shot so far:

function          


        
30条回答
  •  醉话见心
    2020-11-22 08:57

    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 artistoex 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:

    constant count = 1024:

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

提交回复
热议问题