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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With