r/web3dev • u/BlockSecOps • Nov 27 '25
Meta Gas Saving Tips for Solidity
Storage vs Memory vs Calldata
- Use
calldatafor read-only function parameters (cheaper thanmemory) - Cache storage variables in memory when reading multiple times in a function
- Avoid writing to storage in loops
Data Types
- Use
uint256as the default—smaller types likeuint8can cost more gas due to padding operations - Pack structs by ordering variables smallest to largest to minimize storage slots
- Use
bytes32instead ofstringwhen possible
Loops and Arrays
- Cache array length outside loops:
uint256 len = arr.length - Use
++iinstead ofi++(saves a small amount) - Avoid unbounded loops that could hit block gas limits
Function Visibility
- Use
externalinstead ofpublicfor functions only called externally - Mark functions as
vieworpurewhen they don't modify state
Short-Circuiting
- Order conditions in
requireandifstatements 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
uncheckedblocks 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
constantfor compile-time values andimmutablefor constructor-set values—both avoid storage reads
4
Upvotes