String Fill (v3)

Revision 3 of this benchmark created on


Description

Fastest way to create a string with n characters

Setup

var sm = 10,
        md = 100,
        lg = 1000,
        xl = 2000;
    
    
    function arrayJoin(len) {
        return new Array(len + 1).join('0');
    }
    
    function arrayJoinPrototype(len) {
        return Array.prototype.join.call({
            length: len + 1
        }, '0');
    }
    
    function stringConcatLoop(len) {
        var s = '';
        while (len--) s += '0';
        return s;
    }
    
    function stringConcatDoublerLoop(len) {
        var halfLen = len / 2,
            char = '0';
        while (char.length <= halfLen) char += char;
        return char + char.substring(0, len - char.length);
    }
    
    function doubler(len) {
        var result = "0";
        while (result.length < len) result += result;
        return result.slice(0, len);
    }
    
    function stringReplacer(len) {
        return Array(len + 1).toString().replace(/./ig, '0');
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Array Join
arrayJoin(sm);
arrayJoin(md);
arrayJoin(lg);
arrayJoin(xl);
ready
Array Join (Prototype)
arrayJoinPrototype(sm);
arrayJoinPrototype(md);
arrayJoinPrototype(lg);
arrayJoinPrototype(xl);
ready
String Concat Loop
stringConcatLoop(sm);
stringConcatLoop(md);
stringConcatLoop(lg);
stringConcatLoop(xl);
ready
String Concat Doubler Loop
stringConcatDoublerLoop(sm);
stringConcatDoublerLoop(md);
stringConcatDoublerLoop(lg);
stringConcatDoublerLoop(xl);
ready
Replace String
stringReplacer(sm);
stringReplacer(md);
stringReplacer(lg);
stringReplacer(xl);
ready
Doubler
doubler(sm);
doubler(md);
doubler(lg);
doubler(xl);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.