MCPcopy Index your code
hub / github.com/nodejs/node / checkIfCollectableByCounting

Function checkIfCollectableByCounting

test/common/gc.js:149–180  ·  view source on GitHub ↗

* This requires --expose-internals. * This function can be used to check if an object factory leaks or not by * iterating over the heap and count objects with the specified class * (which is checked by looking up the prototype chain). * @param {(i: number) => number} fn The factory receiving ite

(fn, ctor, count, waitTime = 20)

Source from the content-addressed store, hash-verified

147 * @param {number} waitTime Optional breathing time for GC.
148 */
149async function checkIfCollectableByCounting(fn, ctor, count, waitTime = 20) {
150 const { queryObjects } = require('v8');
151 const { name } = ctor;
152 const initialCount = queryObjects(ctor, { format: 'count' });
153 console.log(`Initial count of ${name}: ${initialCount}`);
154 let totalCreated = 0;
155 for (let i = 0; i < count; ++i) {
156 const created = await fn(i);
157 totalCreated += created;
158 console.log(`#${i}: created ${created} ${name}, total ${totalCreated}`);
159 await wait(waitTime); // give GC some breathing room.
160 const currentCount = queryObjects(ctor, { format: 'count' });
161 const collected = totalCreated - (currentCount - initialCount);
162 console.log(`#${i}: counted ${currentCount} ${name}, collected ${collected}`);
163 if (collected > 0) {
164 console.log(`Detected ${collected} collected ${name}, finish early`);
165 return;
166 }
167 }
168
169 await wait(waitTime); // give GC some breathing room.
170 const currentCount = queryObjects(ctor, { format: 'count' });
171 const collected = totalCreated - (currentCount - initialCount);
172 console.log(`Last count: counted ${currentCount} ${name}, collected ${collected}`);
173 // Some objects with the prototype can be collected.
174 if (collected > 0) {
175 console.log(`Detected ${collected} collected ${name}`);
176 return;
177 }
178
179 throw new Error(`${name} cannot be collected`);
180}
181
182module.exports = {
183 checkIfCollectable,

Calls 5

requireFunction · 0.50
queryObjectsFunction · 0.50
fnFunction · 0.50
waitFunction · 0.50
logMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…