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

I played with jsperf.com and found that the prototype 40x function is slower than the default declared function.

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

against.

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

Here's a jsperf test case

PS I know that the modification of the prototype is not the best option and can be called the "monkey patch" :)

+6
source share
2 answers

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

This also explains the performance improvement of new Object("hi").foo() compared to "hi".foo() .

From MDN docs :

String literals (denoted by double or single quotes) and strings returned from String calls in the context of a non-constructor (i.e., without using a new keyword) are primitive strings. JavaScript automatically converts primitives and String objects so that you can use String object methods for primitive strings. In contexts in which a method must be called in a primitive string or when searching for properties, JavaScript will automatically wrap the primitive of the string and invoke the method or search for properties.

Beside:

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

String object versus literal - prototype change?

+6
source

The odds are very good in that you replace the primitive function implemented in C / machine code with the JavaScript body in the headless version.

+1
source

Source: https://habr.com/ru/post/909796/


All Articles