Triggering GC Exercise
Description
JavaScript is a dynamic language. JavaScript programmers constantly create objects and then toss them to the wind and never use them again. This means that the JavaScript engine must be smart about how it manages objects in memory.
We have learned how the JavaScript engines use "Garbage Collection" to mark unused allocations and sweep them up to free them.
In this exercise we will attempt to trigger and log a garbage collection run in both JSC and V8.
Trigger a GC in V8
Run V8 with the --trace-gc
flag to log garbage collection runs.
exercise run v8 --trace-gc
Trigger a garbage collection. There are several ways to do this.
Reveal Answer
Try creating lots of objects in a loop
- What "type" of garbage collection was triggered?
- What happens if you create a number of large array buffers?
- What if you use
%CollectGarbage(0)
?
Trigger a GC in JSC
Run JSC with --logGC=true
to log garbage collection runs.
exercise run jsc --logGC=true
Like before, trigger a garbage collection.
- Are your collection runs "eden" runs or full runs?
Write a
gc()
Function
If you are targeting a bug involving the garbage collector, you may want to trigger a garbage collection at will.
Try to create a function which will cause a garbage collection to run when called. See if you can limit it to a single garbage collection run.
Example Solution
JavaScriptfunction gc() {
for (let i = 0; i < 10; i++) {
new ArrayBuffer(1024 * 1024 * 10);
}
}