Garbage Collection
QuickJS uses automatic garbage collection with configurable thresholds. These functions allow you to control and trigger garbage collection.JS_RunGC
Manually triggers garbage collection.Parameters
JSRuntime *
required
The runtime to run garbage collection on.
Description
Immediately runs a garbage collection cycle on the runtime. This will:- Mark all reachable objects
- Free all unreachable objects
- Call finalizers for freed objects
- Reclaim memory
- Freeing memory at strategic points (e.g., between requests)
- Testing and debugging memory leaks
- Ensuring cleanup before measuring memory usage
- Controlling GC timing in performance-critical code
Garbage collection is already automatic. You typically don’t need to call this function unless you have specific timing or memory requirements.
Example
Example: Periodic GC
Example: Debug Memory Leaks
JS_SetGCThreshold
Sets the garbage collection threshold.Parameters
JSRuntime *
required
The runtime to configure.
size_t
required
Number of bytes to allocate before triggering automatic garbage collection.
Description
Controls how frequently automatic garbage collection runs. When total allocated memory increases bygc_threshold bytes since the last GC, a new GC cycle is triggered.
Lower threshold:
- More frequent GC cycles
- Lower peak memory usage
- Higher CPU overhead
- More predictable memory usage
- Less frequent GC cycles
- Higher peak memory usage
- Lower CPU overhead
- Better performance for allocation-heavy code
The default GC threshold is automatically set based on runtime characteristics. You typically only need to adjust this for performance tuning or memory-constrained environments.
Example
Example: Memory-Constrained Device
Example: Performance Tuning
JS_GetGCThreshold
Retrieves the current garbage collection threshold.Parameters
JSRuntime *
required
The runtime to query.
Returns
size_t
The current GC threshold in bytes.