为什么原型函数比默认声明的函数慢40倍? [英] Why is prototype function 40x slower than the default declared function?

查看:44
本文介绍了为什么原型函数比默认声明的函数慢40倍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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

这是一个jsperf测试用例

P.S.我知道原型修改不是最好的情况,可以命名为猴子修补":)

解决方案

我认为这很慢,因为字符串基元会在每次每次自动被临时对象包装的情况下被调用.

>

这也解释了 new Object("hi").foo()相对于"hi" .foo()的性能提升.

MDN文档:

在非构造函数上下文中(即,不使用new关键字),字符串文字(用双引号或单引号引起来)和从String调用返回的字符串是原始字符串.JavaScript自动转换基元和String对象,以便可以将String对象方法用于基元字符串.在要在原始字符串上调用方法或发生属性查找的情况下,JavaScript将自动包装字符串原始并调用该方法或执行属性查找.

附近:

为什么我不能添加属性到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

Here's a jsperf test case

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆