Skill 5.3.1

Apply gas optimisation techniques in Solidity

Key Concepts

Because storage is the largest cost, most optimisations reduce storage access. Packing places variables smaller than 32 bytes next to each other so that they share a slot, for example a uint128, a uint64 and a uint64 in one slot instead of three uint256 slots. Caching a storage variable in a local variable before a loop replaces repeated SLOADs with cheap stack reads. constant and immutable values avoid storage entirely.

Other techniques: declare external array parameters as calldata; use custom errors instead of long revert strings; emit events for data that only off-chain systems need; avoid unbounded loops; use unchecked for arithmetic that provably cannot overflow, such as an incrementing loop index; and short-circuit cheap conditions before expensive ones. Enabling the optimizer with a suitable runs value applies many low-level optimisations automatically.

Optimisation must never weaken safety: removing checks, using unchecked where overflow is possible or replacing audited code with clever assembly to save a little gas creates far larger risks.