Skip to content

Instantly share code, notes, and snippets.

@greggman
Created June 6, 2025 23:35
Show Gist options
  • Save greggman/7692aec55a7b383893582706fd3767e7 to your computer and use it in GitHub Desktop.
Save greggman/7692aec55a7b383893582706fd3767e7 to your computer and use it in GitHub Desktop.
gc test
/*bug-in-github-api-content-can-not-be-empty*/
/*bug-in-github-api-content-can-not-be-empty*/
//
//import { createRequire } from 'module';
//const require = createRequire(import.meta.url);
//
//const addon = require('./build/Release/test_addon.node');
async function waitForGC(refs) {
while (refs.length) {
gc();
new Array(100 * 1024 * 1024).fill(123);
console.log('waiting for:', refs.map(({id}) => id).join(', '));
await new Promise(resolve => setTimeout(resolve, 1000));
refs = refs.filter(({ ref, id }) => {
const referenced = !!ref.deref();
if (!referenced) {
console.log(`${id} was garbage collected`);
}
return referenced;
});
}
}
function makeJSObjects() {
const a = new Uint32Array(1024*1024);
const b = new Uint32Array(1024*1024);
//a.b = b;
return [new WeakRef(a), new WeakRef(b)];
}
function makeCPPObjects() {
const initialObject = { message: 'Hello from the initial object!' };
const a = new addon.MyClass(initialObject);
const b = new addon.MyClass(initialObject);
//a.setStoredObject(b);
//b.setStoredObject(a);
return [new WeakRef(a), new WeakRef(b)];
}
async function main() {
const [jsRefA, jsRefB] = makeJSObjects();
await waitForGC([
{ ref: jsRefA, id: 'jsA' },
{ ref: jsRefB, id: 'jsB' },
]);
const [refA, refB] = makeCPPObjects();
await waitForGC([
{ ref: refA, id: 'a'},
{ ref: refB, id: 'b'},
]);
}
main();
{"name":"gc test","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment