javascript函数和参数对象,是否涉及成本

标签 javascript performance

在网络和框架中看到这样的代码是很常见的:

var args = Array.prototype.slice.call(arguments);
这样做时,您转换参数 Object变成真正的Array (尽管 JS 有真正的数组)并且它允许你在你的 Array 原型(prototype)中拥有的任何数组方法应用于它,等等。
我记得在某处读到访问 arguments直接对象可能比 Array 克隆或明显选择命名参数慢得多。这有什么道理吗?在什么情况下/浏览器这样做会导致性能损失?你知道关于这个主题的任何文章吗?
更新 来自 http://bonsaiden.github.com/JavaScript-Garden/#function.arguments 的有趣发现这使我以前读过的内容无效...希望这个问题能从 @Ivo Wetzel 之类的人那里得到更多答案谁写的。
在该部分的底部,它说:

Performance myths and truths

The arguments object is always created with the only two exceptions being the cases where it is declared as a name inside of a function or one of its formal parameters. It does not matter whether it is used or not.


这与 http://www.jspatterns.com/arguments-considered-harmful/ 冲突,其中指出:

However, it's not a good idea to use arguments for the reasons of :

  • performance
  • security

The arguments object is not automatically created every time the function is called, the JavaScript engine will only create it on-demand, if it's used. And that creation is not free in terms of performance. The difference between using arguments vs. not using it could be anywhere between 1.5 times to 4 times slower, depending on the browser


显然,不可能两者都是正确的,那么它是哪一个呢?
ECMA 铁杆 Dmitrty Soshnikov 说:

Which exactly “JavaScript engine” is meant? Where did you get this exact info? Although, it can be true in some implementations (yep, it’s the good optimization as all needed info about the context is available on parsing the code, so there’s no need to create arguments object if it was not found on parsing), but as you know ECMA-262-3 statements, that arguments object is created each time on entering the execution context.

最佳答案

Here's一些q&d测试。使用预定义的 arguments似乎是最快的,但这样做并不总是可行的。如果函数的数量事先未知(因此,如果函数可以或必须接收可变数量的参数),我认为调用 Array.prototype.slice一次是最有效的方式,因为在这种情况下 performance loss使用 arguments对象是最小的。

关于javascript函数和参数对象,是否涉及成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5325554/

相关文章:

javascript - 使用 Fetch 将 JSON 放入文档正文中 - Javascript

javascript - Svelte 派生存储和数组排序

ruby - 现代计算机的功能是否不足以处理字符串而无需使用符号(在 Ruby 中)

performance - 这个 Clojure 代码可以优化吗?

mysql - SELECT WHERE IN(子查询)慢

multithreading - 当线程数翻倍时,我的矩阵乘法程序需要四倍的时间

javascript - jQuery toggleClass fade 适用于一个类,而不适用于另一个类?

javascript - Canvas 变换未按预期运行

javascript - 为什么我通过点击获得用户的所有模型而不是一键模型?

java - 为什么从 Java 12 开始 JVM 启动速度更快