扩展String.prototype性能表明函数调用快了10倍

时间:2016-07-16 04:36:41

标签: javascript performance

我想用一些实用方法扩展String对象原型。它起作用了,但性能却低得惊人。将字符串传递给函数比覆盖执行相同操作的String.prototype方法快10倍。为了确保实现这一点,我创建了一个非常简单的count()函数和相应的方法。

(我正在尝试,并创建了该方法的三个不同版本。)

function count(str, char) {
    var n = 0;
    for (var i = 0; i < str.length; i++) if (str[i] == char) n++;
    return n;
}

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

String.prototype.count_reuse = function (char) {
    return count(this, char)
}

String.prototype.count_var = function (char) {
    var str = this;
    var n = 0;
    for (var i = 0; i < str.length; i++) if (str[i] == char) n++;
    return n;
}

// Here is how I measued speed, using Node.js 6.1.0

var STR ='0110101110010110100111010011101010101111110001010110010101011101101010101010111111000';
var REP = 1e3//6;

console.time('func')
for (var i = 0; i < REP; i++) count(STR,'1')
console.timeEnd('func')

console.time('proto')
for (var i = 0; i < REP; i++) STR.count('1')
console.timeEnd('proto')

console.time('proto-reuse')
for (var i = 0; i < REP; i++) STR.count_reuse('1')
console.timeEnd('proto-reuse')

console.time('proto-var')
for (var i = 0; i < REP; i++) STR.count_var('1')
console.timeEnd('proto-var')

结果:

func: 705 ms
proto: 10011 ms
proto-reuse: 10366 ms
proto-var: 9703 ms

正如您所看到的,差异是戏剧性的。

下面证明方法调用的性能可以忽略不计,并且函数代码 it self 对于方法来说速度较慢。

function count_dummy(str, char) {
    return 1234;
}

String.prototype.count_dummy = function (char) {
    return 1234; // Just to prove that accessing the method is not the bottle-neck.
}

console.time('func-dummy')
for (var i = 0; i < REP; i++) count_dummy(STR,'1')
console.timeEnd('func-dummy')

console.time('proto-dummy')
for (var i = 0; i < REP; i++) STR.count_dummy('1')
console.timeEnd('proto-dummy')

console.time('func-dummy')
for (var i = 0; i < REP; i++) count_dummy(STR,'1')
console.timeEnd('func-dummy')

结果:

func-dummy: 0.165ms
proto-dummy: 0.247ms

尽管重复次数很大(如1e8),原型方法的证明速度比函数慢10倍,但在这种情况下可以忽略不计。

所有这些只与String对象有关,因为简单的通用对象在将它们传递给函数或调用它们的方法时执行的操作大致相同:

var A = { count: 1234 };

function getCount(obj) { return obj.count }

A.getCount = function() { return this.count }

console.time('func')
for (var i = 0; i < 1e9; i++) getCount(A)
console.timeEnd('func')

console.time('method')
for (var i = 0; i < 1e9; i++) A.getCount()
console.timeEnd('method')

结果:

func: 1689.942ms
method: 1674.639ms

我一直在搜索Stackoverflow和binging,但其他建议“不要因为污染名称空间而扩展字符串或数组”(这对我的特定项目来说不是问题),我找不到任何与之相关的内容性能方法与功能相比。因此,我应该忘记由于添加方法的性能下降而延长String对象,还是有更多关于它的内容?

1 个答案:

答案 0 :(得分:5)

这很可能是因为您没有使用严格模式,并且您的方法中的this值需要强制转换为String实例而不是原始字符串。

您可以通过在var STR = new String('01101011…')上重复测量来确认这一点。

然后修复您的实施:

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;
};