Skip to main content

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:

  1. Use appropriate data types
  2. Use mappings over arrays
  3. Use fixed-sized arrays over dynamic
  4. Minimize on-chain data and leverage events
  5. Enable Solidity compiler optimization
  6. Precompute data off-chain whenever possible
  7. Use constants and immutable variables
  8. Short-circuit conditionals
  9. Pack variables to optimize storage
  10. Use well-tested libraries
  11. Utilize external visibility modifier
  12. Utilize indexed events
  13. 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)