Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is prototype function 40x slower than the default declared function?

I've played with jsperf.com and found that prototyped function is 40x slower than "default" declared function.

String.prototype.contains = function(s){ return !!~this.indexOf(s) } = 220K ops/s

vs.

function isContains(str, s) { return !!~str.indexOf(s) } = 8.5KK ops/s

Here's a jsperf test case

P.S. I know that prototype modification isn't the best case and can be named 'monkey patching' :)

like image 645
mjey Avatar asked Mar 02 '12 04:03

mjey


People also ask

Does prototype improve memory optimization?

'Prototype' helps remove code redundancy which helps boost your app's performance. If you are seeking to optimize resources or memory on your application, you should use prototype .

What is prototype function in JavaScript?

A Function object's prototype property is used when the function is used as a constructor with the new operator. It will become the new object's prototype. Note: Not all Function objects have the prototype property — see description.

What is the prototype object in JavaScript and why is it important?

Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.

What is Proto and prototype in JavaScript?

The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.


1 Answers

I think it is slow because the string primitive is automatically wrapped with a temporary object each time a method is called.

This also explains the performance boost of new Object("hi").foo() over "hi".foo().

From the MDN docs:

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings. JavaScript automatically converts primitives and String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

Nearby:

Why can't I add properties to a string object in javascript?

String object versus literal - modifying the prototype?

like image 197
Dagg Nabbit Avatar answered Oct 06 '22 00:10

Dagg Nabbit