简体   繁体   English

Javascript - 在V8中添加到String.prototype的函数性能不佳?

[英]Javascript - poor performance in V8 of functions added to String.prototype?

I've been using some code to extract unsigned 16 bit values from a string. 我一直在使用一些代码从字符串中提取无符号的16位值。

I discovered that adding this function to the prototype for String : 我发现将此函数添加到String的原型中:

String.prototype.UInt16 = function(n) {
    return this.charCodeAt(n) + 256 * this.charCodeAt(n + 1);
};

is much slower than just having a function which takes a String as a parameter: 比只有一个以String作为参数的函数要慢得多:

var UInt16 = function(s, n) {
    return s.charCodeAt(n) + 256 * s.charCodeAt(n + 1);
};

In Firefox the difference is only a factor of two, but in Chrome 15 it's one hundred times slower! 在Firefox中,差异仅为两倍,但在Chrome 15中它的速度要慢一百倍

See results at http://jsperf.com/string-to-uint16 请参阅http://jsperf.com/string-to-uint16上的结果

Can anyone proffer an explanation for this, and/or offer an alternative way of using the prototype without the performance hit? 任何人都可以为此提供解释,和/或提供使用原型的替代方法,而不会影响性能吗?

Accessing prototype from a primitive (because it's not an object) is much slower than accessing prototype from an object. 从基元访问原型(因为它不是对象)比从对象访问原型要慢得多。

http://jsperf.com/string-to-uint16/2 http://jsperf.com/string-to-uint16/2

10x faster in chrome and 2x faster in firefox for me. 对于我来说,Chrome的速度提高了10倍,而Firefox的速度提高了2倍。

Is there an actual bottleneck in using the prototype? 使用原型是否存在实际瓶颈? It's still very fast if you don't need millions of ops per second. 如果你每秒不需要数百万的操作,它仍然非常快。 If you need, then just use a function. 如果需要,那么只需使用一个功能。

Alnitak , I made a quick jsperf test (which I accidentally published), and it shows that prototypes to user types aren't slower. Alnitak ,我做了一个快速的jsperf 测试 (我不小心发布了),它表明用户类型的原型并不慢。 When considering how engines like V8 works, it makes sense that the Java compilation will behave much differently when adding code to built-in objects. 在考虑像V8这样的引擎是如何工作的时候,在将代码添加到内置对象时,Java编译的行为会有很大不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM