Extending String.prototype performance shows that function calls are 10x faster

This is most likely because you are not using strict mode, and the this value inside your method is getting coerced to a String instance instead of being a primitive string. This coercion, and further method calls or property accesses on the String object, are slower than using primitive values.

You can (Edit: could, at least, in 2016) confirm this by repeating your measurement on var STR = new String('01101011…') which should have less overhead.

Then fix your implementation:

String.prototype.count = function (char) {
    "use strict";
//  ^^^^^^^^^^^^
    var n = 0;
    for (var i = 0; i < this.length; i++)
        if (this[i] == char)
            n++;
    return n;
};

Leave a Comment