Memory Management
QuickJS provides fine-grained control over memory allocation, including limits, custom allocators, and garbage collection configuration.
Memory Limits
Setting Memory Limits
Prevent runaway scripts from consuming all available memory:
Signature:
When the limit is reached, allocations fail and JavaScript code throws an out-of-memory exception.
Monitoring Memory Usage
Signature:
Pretty Print Memory Usage
This produces a detailed report including:
- Total memory allocated
- Memory used by objects, strings, arrays
- Function bytecode size
- Shape and property statistics
Custom Memory Allocators
Allocator Interface
Replace QuickJS’s default allocator with your own:
Custom Allocator Example
Signature:
Opaque Pointer
Access your allocator state:
Signatures:
Garbage Collection
GC Threshold
Control when automatic GC is triggered:
Signatures:
The GC runs automatically when memory usage exceeds the threshold.
Manual GC
Trigger garbage collection manually:
Signature:
Check Object Liveness
Signature:
Stack Size Limits
Maximum Stack Size
Prevent stack overflow in deeply recursive JavaScript:
Signature:
Default: JS_DEFAULT_STACK_SIZE (1 MB)
Updating Stack Top
When switching threads, update the stack top:
Signature:
Memory Allocation Helpers
Runtime Allocators
Allocate memory using the runtime’s allocator:
Signatures:
Context Allocators
Allocate memory from a context:
Signatures:
SharedArrayBuffer
Custom SAB Allocator
Provide a custom allocator for SharedArrayBuffer:
Signature:
Debugging Memory Leaks
Enable Leak Detection
Dump flags (from quickjs.h):
Signatures:
Runtime Finalizers
Run cleanup code when the runtime is freed:
Signature:
Finalizers run in LIFO order. The runtime is no longer usable at this point.
Best Practices
- Always set memory limits for untrusted code
- Monitor memory usage in production with
JS_ComputeMemoryUsage()
- Use custom allocators to integrate with your app’s memory system
- Tune GC threshold based on your workload (lower = more frequent GC)
- Free values promptly - don’t rely solely on GC
- Test with leak detection enabled during development
Next Steps
- Performance - Optimize memory usage patterns
- Embedding - Integrate memory management with your app
- Workers - Understand per-worker memory isolation