【问题标题】:Will the "arguments" object prevent garbage collection for unbound arguments?“参数”对象会阻止未绑定参数的垃圾收集吗?
【发布时间】:2020-09-23 13:11:13
【问题描述】:

如果我有一个“接受”两个参数的函数sum,则返回一个将在“长时间”内解决的承诺。传递给sum 的任何参数(经过前两个参数)是否会保留在内存中,并且不会被垃圾回收?

例如,sum 会阻止“大对象”FOO 被垃圾回收吗?

const sum = (a, b) => new Promise((resolve) => {
  setTimeout(() => resolve(a+b), 500 /* Lets pretend this is a huge number */);
});

(async () => {
  const s = await sum(2, 3, {/* Some large object, FOO */});
  console.log(s);
})();

我假设因为您可以通过“参数”对象访问 FOO,那么 FOO 是否需要保存在内存中?但是,由于箭头函数中无法访问“参数”,因此关键字函数和箭头函数之间的这种行为会有所不同吗?

function sum(a, b) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(...arguments);
      resolve(a+b);
    }, 500 /* Lets pretend this is a huge number */);
  });
};

const arrowSum = (a, b) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(...arguments);
      resolve(a+b);
    }, 500 /* Lets pretend this is a huge number */);
  });
};

(async () => {
  const s = await sum(2, 3, {/* Some large object, FOO */});
  console.log(s);
  
  const arrowS = await arrowSum(2, 3, {/* Some large object, FOO */});
  console.log(arrowS);
})();

【问题讨论】:

    标签: javascript garbage-collection arguments


    【解决方案1】:

    来自twitter thread with Surma(谷歌工程师)。

    问:“参数”对象会阻止对未绑定参数进行垃圾收集吗?
    答:很可能是的。您可以通过 eval() 访问arguments,因此引擎/编译器永远无法证明您不会访问它并放开该对象。

    问:既然“参数”在箭头函数中不起作用,那是否会使箭头函数的性能更高,因为消费者滥用不会导致像关键字函数会?
    答:理论上,我猜箭头函数在这里会有一个普通函数没有的优化。

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      相关资源
      最近更新 更多