为什么原型函数比默认声明的函数慢40倍? [英] Why is prototype function 40x slower than the default declared function?
问题描述
我在jsperf.com上玩过,发现原型函数比声明的默认"函数慢 40倍.
String.prototype.contains = function(s){return !!〜this.indexOf(s)}
= 220K ops/s
vs.
函数isContains(str,s){return !!〜str.indexOf(s)}
= 8.5KK ops/s
P.S.我知道原型修改不是最好的情况,可以命名为猴子修补":)
我认为这很慢,因为字符串基元会在每次每次自动被临时对象包装的情况下被调用.
>这也解释了 new Object("hi").foo()
相对于"hi" .foo()
的性能提升.
从 MDN文档:
在非构造函数上下文中(即,不使用new关键字),字符串文字(用双引号或单引号引起来)和从String调用返回的字符串是原始字符串.JavaScript自动转换基元和String对象,以便可以将String对象方法用于基元字符串.在要在原始字符串上调用方法或发生属性查找的情况下,JavaScript将自动包装字符串原始并调用该方法或执行属性查找.
附近:
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
P.S. I know that prototype modification isn't the best case and can be named 'monkey patching' :)
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?
这篇关于为什么原型函数比默认声明的函数慢40倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!