Roadmap › Solidity & Smart Contract Development › Module: Advanced Topics
Lessons in this course (11)
10. Gas optimisation
AdvancedMediumLesson 10 of 11
- Minimise storage writes; cache storage reads in local variables (
uint256 bal = balances[a];). - Pack variables into 32-byte slots (
uint128 a; uint128 b;share one slot; order struct fields by size). constantandimmutablefor fixed values (no storage reads).calldatainstead ofmemoryfor external read-only params.- Custom errors instead of revert strings.
- Use
mappingover arrays for lookups; avoid unbounded loops. unchecked { ++i; }in loops where overflow is impossible;++ivsi++(minor).- Emit events instead of storing data that only off-chain apps need.
- Short-circuit conditions (cheap checks first);
externaloverpublicfor functions not called internally (minor in modern compilers). - Batch operations; use transient storage for in-transaction flags.
- Enable the optimizer (
runstuned: low for deploy cost, high for call cost); compare withforge snapshot/ gas reports.
Readability and security beat micro-optimisation — measure first.