String.prototype.replicate (v2)

Revision 2 of this benchmark created on


Setup

let x = 1e6

Test runner

Ready to run.

Testing in
TestOps/sec
O(log n) iterative
/**
 * @param {Number} times
 * @return {String}
 */
String.prototype.replicate = function (times) {
    let result = this, tail = ""
    for (; times > 1; times >>= 1) {
        if (times & 1) tail += result
        result += result
    }

    return result + tail
}

"a".replicate(x)
ready
O(log n) recursive
/**
 * @param {Number} times
 * @return {String}
 */
String.prototype.replicate = function (times) {
    if (times < 2) return this

    let result = (this + this).replicate(times >> 1)
    if (times & 1) result += this

    return result
}

"a".replicate(x)
ready
O(n)
/**
 * @param {Number} times
 * @return {String}
 */
String.prototype.replicate = function (times) {
    let result = this
    for (let i = 1; i < times; i++) {
        result += this;
    }

    return result
}

"a".replicate(x)
ready

Revisions

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