Alnitak
Alnitak

Reputation: 339786

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?

Upvotes: 5

Views: 838

Answers (2)

Keldon Alleyne
Keldon Alleyne

Reputation: 2130

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.

Upvotes: 0

Esailija
Esailija

Reputation: 140210

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.

Upvotes: 1

Related Questions