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)
Links
Questions
Which engineering decision related to this topic has the highest switching cost once made — and how do you make it well with incomplete information?
- At what scale or complexity level does the right answer to this topic change significantly?
- How does the introduction of AI-native workflows change the conventional wisdom about this technology?
- Which anti-pattern in this area is most commonly introduced by developers who know enough to be dangerous but not enough to know what they don't know?