Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 742
Alnitak Avatar asked Nov 14 '22 13:11

Alnitak


1 Answers

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.

like image 57
Esailija Avatar answered Nov 16 '22 02:11

Esailija