Roadmap › Solidity & Smart Contract Development › Module: Advanced Topics
Lessons in this course (11)

10. Gas optimisation

AdvancedMediumLesson 10 of 11
  1. Minimise storage writes; cache storage reads in local variables (uint256 bal = balances[a];).
  2. Pack variables into 32-byte slots (uint128 a; uint128 b; share one slot; order struct fields by size).
  3. constant and immutable for fixed values (no storage reads).
  4. calldata instead of memory for external read-only params.
  5. Custom errors instead of revert strings.
  6. Use mapping over arrays for lookups; avoid unbounded loops.
  7. unchecked { ++i; } in loops where overflow is impossible; ++i vs i++ (minor).
  8. Emit events instead of storing data that only off-chain apps need.
  9. Short-circuit conditions (cheap checks first); external over public for functions not called internally (minor in modern compilers).
  10. Batch operations; use transient storage for in-transaction flags.
  11. Enable the optimizer (runs tuned: low for deploy cost, high for call cost); compare with forge snapshot / gas reports.

Readability and security beat micro-optimisation — measure first.