Cargo Profile Settings
Configure yourCargo.toml with optimized release profile settings:
Profile Configuration Breakdown
opt-level = āzā
Optimizes for minimal binary size, which is critical for smart contracts:"0"- No optimization (fastest compilation)"1"- Basic optimization"2"- Default release optimization"3"- Maximum optimization for speed"s"- Optimize for size"z"- Aggressively optimize for size (recommended)
lto = true
Link Time Optimization allows cross-crate optimization:codegen-units = 1
Reduced codegen units improve optimization but slow compilation:Custom Build Profiles
Release with Logs
For debugging production builds while maintaining optimizations:Release without LTO
Useful for faster iteration during development:Development Profile
The default dev profile in Soroban SDK workspace:Code Optimization Patterns
Minimize Storage Operations
Storage operations are expensive. Batch reads and writes:Use Efficient Data Types
Prefer BytesN over Bytes for Fixed Sizes
Use symbol_short! When Possible
Avoid Unnecessary Cloning
Inline Critical Functions
Optimize Loops
Memory Management
Avoid Large Stack Allocations
Reuse Allocations
Contract Size Optimization
Reduce Dependencies
Minimize external crate dependencies:Feature Flags
Use feature flags to conditionally compile code:Avoid Generic Functions When Possible
Generic functions generate code for each type:Compilation Optimization
Use soroban-sdk Macros
The SDK macros generate optimized code:Enable WASM Optimization Tools
wasm-opt
Usewasm-opt from Binaryen for additional optimization:
soroban-cli optimize
The Soroban CLI includes optimization:Measuring Performance
Analyze WASM Size
Profile Build Time
Test Resource Usage
Use test utilities to measure resource consumption:Best Practices Summary
Build Configuration
- ā
Use
opt-level = "z"for release builds - ā
Enable LTO (
lto = true) - ā
Set
codegen-units = 1 - ā
Use
panic = "abort"
Code Patterns
- ā Minimize storage operations
- ā
Use fixed-size types (
BytesN,symbol_short!) - ā Avoid unnecessary cloning
- ā Use inline annotations strategically
- ā Prefer iterators over indexed loops
Memory Management
- ā Avoid large stack allocations
- ā Reuse allocations when possible
- ā Use appropriate data structures
Build Process
- ā Minimize dependencies
- ā Use feature flags
- ā
Run
wasm-optorsoroban contract optimize - ā Measure and profile regularly
Common Anti-Patterns
ā Excessive Logging
ā Unused Code
#[allow(dead_code)] carefully and remove truly unused code.
ā Large Match Statements
Optimization Checklist
Before deploying:- Configured optimal Cargo profile settings
- Minimized storage operations
- Used appropriate data types
- Removed debug code and logs
- Ran
cargo clippyfor suggestions - Optimized WASM with
wasm-optor Soroban CLI - Measured contract size and resource usage
- Tested with realistic workloads
- Profiled gas costs
- Reviewed for dead code