Performance Tuning and Optimization
QuickJS is designed to be small and efficient. This guide covers techniques to optimize performance for your specific use case.Build Options
Compiler Optimizations
FromCMakeLists.txt, QuickJS supports various build configurations:
-O2 or -O3 optimizations and strip debug symbols.
Disable Parser
For embedded systems where code is pre-compiled, disable the parser:qjsc.
Static Builds
Create standalone executables with no runtime dependencies:Sanitizers (Development Only)
Enable sanitizers to catch bugs that may affect performance:Memory Optimization
Tune GC Threshold
Balance memory usage vs. GC frequency:Set Memory Limits
Prevent memory bloat:Minimize Context Count
Each context has overhead. Share contexts when possible:Use Bytecode Compilation
Pre-compile scripts to bytecode:Execution Optimization
Stack Size Configuration
Adjust stack size based on your recursion needs:JS_DEFAULT_STACK_SIZE (1 MB).
Minimize JSValue Conversions
Conversions between C and JavaScript types have overhead:Avoid Unnecessary Exception Checks
Exception checks have minimal overhead, but can add up:Function Call Optimization
Direct C Function Calls
Use C functions instead of JavaScript for performance-critical code:Function Magic Numbers
Use magic numbers to create specialized versions:ArrayBuffer and Typed Arrays
Zero-Copy Buffers
Share memory between C and JavaScript:Direct Buffer Access
Access buffers without copying:Interrupt Handler
Timeout Implementation
The interrupt handler is called periodically during execution. Keep it fast!
Module Loading
Optimize Module Resolution
Cache module loading to avoid repeated file I/O:Profiling
Enable Bytecode Dumps
Measure Execution Time
JavaScript-Level Optimizations
While this guide focuses on C API, remember these JavaScript best practices:- Avoid
eval()andnew Function()- they prevent JIT optimization - Use typed arrays for numeric data instead of regular arrays
- Minimize property access in tight loops
- Prefer
constandletovervar - Use strict mode (
"use strict")
Benchmarking
Example benchmark harness:Next Steps
- Memory Management - Deep dive into allocation strategies
- Native Modules - Optimize C module performance
- Workers - Parallelize with worker threads