gc.js (1604B)
1 /** 2 * Does a best-effort attempt at invoking garbage collection. Attempts to use 3 * the standardized `TestUtils.gc()` function, but falls back to other 4 * environment-specific nonstandard functions, with a final result of just 5 * creating a lot of garbage (in which case you will get a console warning). 6 * 7 * This should generally only be used to attempt to trigger bugs and crashes 8 * inside tests, i.e. cases where if garbage collection happened, then this 9 * should not trigger some misbehavior. You cannot rely on garbage collection 10 * successfully trigger, or that any particular unreachable object will be 11 * collected. 12 * 13 * @returns {Promise<undefined>} A promise you should await to ensure garbage 14 * collection has had a chance to complete. 15 */ 16 self.garbageCollect = async () => { 17 // https://testutils.spec.whatwg.org/#the-testutils-namespace 18 if (self.TestUtils?.gc) { 19 return TestUtils.gc(); 20 } 21 22 // Use --expose_gc for V8 (and Node.js) 23 // to pass this flag at chrome launch use: --js-flags="--expose-gc" 24 // Exposed in SpiderMonkey shell as well 25 if (self.gc) { 26 return self.gc(); 27 } 28 29 // Present in some WebKit development environments 30 if (self.GCController) { 31 return GCController.collect(); 32 } 33 34 console.warn( 35 'Tests are running without the ability to do manual garbage collection. ' + 36 'They will still work, but coverage will be suboptimal.'); 37 38 for (var i = 0; i < 1000; i++) { 39 gcRec(10); 40 } 41 42 function gcRec(n) { 43 if (n < 1) { 44 return {}; 45 } 46 47 let temp = { i: "ab" + i + i / 100000 }; 48 temp += "foo"; 49 50 gcRec(n - 1); 51 } 52 };