SO

Solidity Gas Optimization

Gas optimization patterns for Solidity smart contracts

Details

Language / Topic
soliditySolidity
Category
Performance

Rules

balanced
- Pack related state variables into the same 32-byte storage slot by declaring smaller types (`uint128`, `uint64`, `bool`) consecutively.
- Use `calldata` instead of `memory` for function parameters that are not modified — `calldata` reads directly from the input without copying.
- Cache storage reads in local variables (`uint256 _balance = balance[msg.sender]`) when reading the same slot more than once in a function.
- Use `unchecked { ++i; }` in loops where overflow is provably impossible — it saves the overflow check gas on each iteration.
- Prefer `mapping` over arrays for large data sets — array iteration costs O(n) gas while mapping lookups cost O(1).
- Use events to store historical data instead of state variables — event logs are far cheaper than storage and sufficient for off-chain queries.
- Declare functions `view` or `pure` when they do not modify state — these calls are free when called externally and clearly signal their intent.