[] .map.call()与Array.prototype.map.call()? [英] [].map.call() VS Array.prototype.map.call()?

查看:112
本文介绍了[] .map.call()与Array.prototype.map.call()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么一个人比另一个人更受青睐?

Why would one be preferred over the other?

[].map.call(...)

Array.prototype.map.call(...)

jsPerf 中进行快速测试表明Array.prototype方法性能更高,尽管我在某处读到jsPerf的结果可能具有欺骗性.这里不是在讨论jsPerf,而是在寻找为什么为什么一个比另一个更受青睐的见解.谢谢!

Doing a quick test in jsPerf shows the Array.prototype way is more performant, although I read somewhere that jsPerf results can be deceiving. Not here to debate jsPerf, rather, just looking for some insight on why one would be preferred over the other. Thanks!

推荐答案

[].mapArray.prototype.map的值(在没有恶作剧的情况下)相同. [].map表达式涉及(至少从概念上讲;可以对其进行优化)可能会构造一个新的Array实例,从而可能(对性能影响很小).

The values of [].map and Array.prototype.map are (in the absence of shenanigans) identical. The expression [].map involves (at least conceptually; it could be optimized away possibly) the construction of a new Array instance, so that could have (extremely minor) performance implications.

表达式[].map创建一个新的空数组,然后引用其"map"属性.除非添加一个数组实例,否则它没有"map"属性,因此不会在对象本身上找到它.因此,运行时将检查原型链上的下一个对象,当然是Array.prototype对象.运行时 将在其中找到一个地图"属性—具体来说,是Array.prototype.map.这就是为什么他们是同一回事.

The expression [].map creates a new empty array, and then references its "map" property. Array instances don't have a "map" property unless you add one, so it won't be found on the object itself. The runtime will therefore check the next thing on the prototype chain, which is of course the Array.prototype object. The runtime will find a "map" property there — specifically, Array.prototype.map. That's why they're the same thing.

{}.toStringObject.prototype.toString具有类似的等效关系.使用模式的主要区别可能是{}.toString出现在表达式的开头可能会引起问题,因为在这种情况下,前导{将被视为语句块{,而不是对象初始化{.但是,{}.toString的典型用法是不太可能需要启动表达式.因此

An analogous equivalence holds for {}.toString and Object.prototype.toString. The main difference in usage patterns may be that {}.toString can cause issues when it appears at the very beginning of an expression, because the leading { in that case will be taken to be a statement block {, not an object initialization {. However, typical uses of {}.toString are such that it's not terribly likely that it'd need to start an expression. Thus

console.log({}.toString.call(someMysteryObject));

效果和

console.log(Object.prototype.toString.call(someMysteryObject));

性能方面,在.map()情况下,使用该方法隐含的函数调用的开销几乎可以肯定会完全压倒找到对.map()函数的引用的两种方式之间的性能差异.一开始.

Performance-wise, in the case of .map(), the overhead of the function calls implicit in the use of that method will almost certainly completely overwhelm the performance difference between the two ways of finding a reference to the .map() function at the start.

这篇关于[] .map.call()与Array.prototype.map.call()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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