Skip to content

Instantly share code, notes, and snippets.

@justjavac justjavac/gc-track.js
Last active Sep 28, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

justjavac commented Sep 17, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.