Create a string of variable length, filled with a repeated character

前端 未结 10 1117
刺人心
刺人心 2020-11-28 03:59

So, my question has been asked by someone else in it\'s Java form here: Java - Create a new String instance with specified length and filled with specific character. Best so

10条回答
  •  星月不相逢
    2020-11-28 04:37

    Unfortunately although the Array.join approach mentioned here is terse, it is about 10X slower than a string-concatenation-based implementation. It performs especially badly on large strings. See below for full performance details.

    On Firefox, Chrome, Node.js MacOS, Node.js Ubuntu, and Safari, the fastest implementation I tested was:

    function repeatChar(count, ch) {
        if (count == 0) {
            return "";
        }
        var count2 = count / 2;
        var result = ch;
    
        // double the input until it is long enough.
        while (result.length <= count2) {
            result += result;
        }
        // use substring to hit the precise length target without
        // using extra memory
        return result + result.substring(0, count - result.length);
    };
    

    This is verbose, so if you want a terse implementation you could go with the naive approach; it still performs betweeb 2X to 10X better than the Array.join approach, and is also faster than the doubling implementation for small inputs. Code:

    // naive approach: simply add the letters one by one
    function repeatChar(count, ch) {
        var txt = "";
        for (var i = 0; i < count; i++) {
            txt += ch;
        }
        return txt;
    }
    

    Further information:

    • Run speed test in your own browser
    • Full source code of speed test
    • Speed test results

提交回复
热议问题