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

前端 未结 2 1916
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 00:08

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

String.prototype.contains =

相关标签:
2条回答
  • 2021-01-03 00:50

    Odds are very good that you're replacing a primitive function implemented in C/machine code with a JavaScript body in the monkey-patched version.

    0 讨论(0)
  • 2021-01-03 01:07

    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?

    0 讨论(0)
提交回复
热议问题