这个功能可以被垃圾收集吗? [英] Can this function be garbage-collected?

查看:125
本文介绍了这个功能可以被垃圾收集吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这块蛋糕......呃,代码:

Consider this piece of cake... ehm, code:

'use strict'

function doWork () {
  return new Promise(function (resolve, reject) {
    // work work work...
    // Done! But... where's the resolve() ???
  })
}

doWork().then(function doMoreWork () {
  // Some more work to do...
})

一旦Promise的构造函数中的函数完成......

Once the function in the Promise's constructor finishes...


  1. 承诺对象是垃圾可收集的吗?

  2. doMoreWork()垃圾收集?

  1. Is the Promise object garbage-collectible?
  2. Is doMoreWork() garbage-collectible?

我猜是 doMoreWork()不能直接进行GC编辑,因为Promise会保留对它的引用,但是一旦promise的主体完成并将执行上下文返回到上层(?)范围,堆栈就会展开(因为这里没有更多的声明可以执行了)Promise变得无法访问,因此是垃圾收集。

My guess is that doMoreWork() cannot be GC-ed directly because the Promise keeps a reference to it, but once the promise's body finishes and returns the execution context to the upper (?) scope, the stack unwinds (because there is no more statements here to be executed) and the Promise becomes unreachable, thus being garbage-collectible.

您能否确认我对此主题的理解是否正确?

Can you confirm that my understanding of this topic is correct?

我如何凭经验观察此行为?换句话说,我如何监控GC-ed的对象以及何时?我纯粹在Node.js中开发,如果这有任何区别。

How could I empirically observe this behaviour? In other words, how can I monitor what objects are being GC-ed and when? I develop purely in Node.js, if that makes any difference.

推荐答案

没有什么可以保留对promise的引用所以它会被垃圾收集。承诺是唯一保持对函数 doMoreWork 的引用,所以它也将被垃圾收集。

There is nothing keeping reference to the promise so it will be garbage collected. The promise is the only thing keeping reference to the function doMoreWork so it will be garbage collected too.


我怎么能凭经验观察这种行为?换句话说,我如何监控哪些对象正在进行GC编辑?何时?我纯粹在Node.js中开发,如果这有任何区别。

How could I empirically observe this behaviour? In other words, how can I monitor what objects are being GC-ed and when? I develop purely in Node.js, if that makes any difference.

V8中的GC不一定会收集对象。例如,如果这是您的整个程序,那么首先运行任何GC都会浪费时间。

The GC in V8 never necessarily collects an object. For instance if this is your whole program, it would be a waste of time to run any GC in the first place.

这篇关于这个功能可以被垃圾收集吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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