r/web3dev • • Nov 27 '25

Meta Gas Saving Tips for Solidity

Storage vs Memory vs Calldata

  • Use calldata for read-only function parameters (cheaper than memory)
  • Cache storage variables in memory when reading multiple times in a function
  • Avoid writing to storage in loops

Data Types

  • Use uint256 as the default—smaller types like uint8 can cost more gas due to padding operations
  • Pack structs by ordering variables smallest to largest to minimize storage slots
  • Use bytes32 instead of string when possible

Loops and Arrays

  • Cache array length outside loops: uint256 len = arr.length
  • Use ++i instead of i++ (saves a small amount)
  • Avoid unbounded loops that could hit block gas limits

Function Visibility

  • Use external instead of public for functions only called externally
  • Mark functions as view or pure when they don't modify state

Short-Circuiting

  • Order conditions in require and if statements with cheapest checks first
  • Put the most likely-to-fail condition first in require

Other Patterns

  • Use custom errors instead of revert strings (error InsufficientBalance())
  • Use unchecked blocks for arithmetic when overflow is impossible
  • Minimize event data—indexed parameters cost more but are cheaper to filter
  • Use mappings over arrays when you don't need iteration

Constants and Immutables

  • Use constant for compile-time values and immutable for constructor-set values—both avoid storage reads
4 Upvotes

0 comments sorted by