简体   繁体   中英

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.

I discovered that adding this function to the prototype for 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:

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!

See results at 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

10x faster in chrome and 2x faster in firefox for me.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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