Solidity Gas Optimization
Strategies to Save Gas
tip
Think of packing the trunk for holiday, you need fill every space in the optimal way and only take what you actually need.
Summary
High level checklist of gas optimization strategies:
- Use appropriate data types
- Use mappings over arrays
- Use fixed-sized arrays over dynamic
- Minimize on-chain data and leverage events
- Enable Solidity compiler optimization
- Precompute data off-chain whenever possible
- Use constants and immutable variables
- Short-circuit conditionals
- Pack variables to optimize storage
- Use well-tested libraries
- Utilize external visibility modifier
- Utilize indexed events
- Thoroughly test your contracts
More Tips
- Tradeoff readability for performance (assembly/inline code instead of function calls) because auditability is crucial for security
- Tradeoff UX for performance (e.g. off-chain indexers for on-chain minimalism)
- Immutables and constants
- Uniswap snapshot testing pattern / hardhat gas table
- Outlining opcodes https://www.evm.codes/,
- MLOAD/MSTORE/SLOAD/SSTORE,
- Caching variables to memory
- Common patterns to save gas - golf course
- Deployment costs
- When to use proxy patterns (user deployments)