Skip to main content

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
Garbage collection normally runs automatically when memory allocation crosses the GC threshold. Manual triggering is useful for:
  • 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 by gc_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
Higher threshold:
  • 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.

Description

Returns the number of bytes that must be allocated before automatic garbage collection triggers.

Example

Example: Adaptive GC

Example: GC Statistics

Best Practices

When to Use Manual GC

Memory-Constrained Configuration

Excessive manual GC calls can hurt performance. Let the automatic GC do its job unless you have specific requirements. Only call JS_RunGC() at strategic points like between requests or after freeing large data structures.