Skip to content

Instantly share code, notes, and snippets.

@justjavac
Last active June 29, 2022 11:43
Show Gist options
  • Save justjavac/96429bb59e49e851ba10de9e46948bd2 to your computer and use it in GitHub Desktop.
Save justjavac/96429bb59e49e851ba10de9e46948bd2 to your computer and use it in GitHub Desktop.
JS中怎样判断某个对象是否被GC回收? https://www.zhihu.com/question/345974014/answer/826236205
// 需要通过 node --allow-natives-syntax 参数运行
const { GCSignal, consumeSignals, trackGarbageCollection } = require("gc-signals");
function fn() {
// 创建两个局部变量
const a1 = new GCSignal(1);
const a2 = new GCSignal(2);
global.tmp = a2; // 将 a2 变量赋值给全局变量
const o = {};
trackGarbageCollection(o, 3); // 跟踪局部变量 o 的 GC 状态,标识为 3
}
let obj = {};
trackGarbageCollection(obj, 4); // 跟踪变量 obj 的 GC 状态,标识为 4
fn();
// 函数内创建了 3 个局部变量 a1、a2、o
// 但是 a2 赋值给了全局变量
// 函数调用完后,a1 和 o 会被释放
%CollectGarbage(null); // V8 Nativa 函数,手动触发 GC
console.log(consumeSignals()); // [1, 3]
obj = undefined;
// obj 原来的值为空对象({}),通过将 obj 设置为 undefined 回收原来的对象
%CollectGarbage(null); // V8 Nativa 函数,手动触发 GC
console.log(consumeSignals()); // [4]
global.tmp = undefined; // 同上
%CollectGarbage(null); // V8 Nativa 函数,手动触发 GC
console.log(consumeSignals()); // [2]
@justjavac
Copy link
Author

需要通过 node --allow-natives-syntax gc-track.js 运行

@Telanx
Copy link

Telanx commented Jan 27, 2022

微信图片_20220128023532
你好,请问下这个问题咋解决???

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment