js (v8) rest参数和垃圾回收

huangapple go评论90阅读模式
英文:

js (v8) rest params and gc

问题

在上面的示例中显然会创建一个数组但是对于下面这种情况呢

```js
function foo(...rest) {
/*...*/
}

在这里,rest 在技术上与 arguments 相同。

function foo() {
   console.log.apply(null, arguments)
}

所以,如果我想避免生成垃圾,是否可以优先使用 arguments 或者不使用它呢?
此外,arguments 是否总是存在,还是仅在函数范围内使用关键字时才存在?
(如果始终存在,我假设使用它可能更好;如果不是,那么在 restarguments 之间是否有任何区别?)


<details>
<summary>英文:</summary>

does rest params allocate array&lt;br/&gt;

```js
function foo(a, b, ...rest) {
/*...*/
}

in example above its obvoius that array created, but what about this case

function foo(...rest) {
/*...*/
}

there rest technicly the same as arguments

function foo() {
   console.log.apply(null, arguments)
}

so, if i want avoid generate garbage could i prefer to use arguments or not ?<br>
also, does arguments exists always or only when keyword used in function scope?<br>
(if always, i assume thet using it is probably better, if not, is there any difference betwin rest and arguments?)

答案1

得分: 2

rest technicly the same as arguments

并不完全相同。剩余参数(rest parameters)创建一个真正的数组,而 arguments 对象 众所周知不是一个数组,但需要转换为数组。而且在松散模式下,它的行为更加奇怪,会别名声明为参数的变量。

Does arguments exists always or only when keyword used in function scope?

只有在函数内的代码引用它时才会被创建 - 这是一种相对简单但影响巨大的优化,不必为每个函数调用分配一个新对象。实际上,在V8中,这种优化有时甚至不会实例化对象,即使代码引用它,参见 https://stackoverflow.com/q/29198195/1048572Crankshaft vs arguments object by Vyacheslav Egorov 了解详细信息。

Is there any difference, should i prefer to use arguments?

在现代代码中,通常应该优先使用剩余参数(rest parameters)。它们更清晰(行为更规范),更声明式(更容易理解),并且是真正的数组(因此可以使用通常的数组方法)。它们是惯用选择。

英文:

> rest technicly the same as arguments

Not really. Rest parameters create a proper array, while the arguments object famously is not an array but needs to be converted to one. And in sloppy mode, it behaves even weirder, aliasing the variables that are declared as parameters.

> Does arguments exists always or only when keyword used in function scope?

It is created only when any code in the function refers to it - this is a relatively trivial optimisation with big impact, not having to allocate a new object for every single function call. And in fact, this optimisation goes even further in V8, sometimes not even instantiating the object even code refers to it, see https://stackoverflow.com/q/29198195/1048572 and Crankshaft vs arguments object by Vyacheslav Egorov for details.

> Is there any difference, should i prefer to use arguments?

In modern code, you should generally prefer rest parameters. They are cleaner (less weird behavior), more declarative (easier to understand), and are actual arrays (so that you can use the usual array methods). They are the idiomatic choice.

huangapple
  • 本文由 发表于 2023年8月10日 15:03:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定