Intermediate
Gas Optimisation Basics — Key concepts
Write cheaper, cleaner code.
Developer Intermediate
3/6 — Gas Optimisation Basics — Key concepts
Why it matters Gas costs are real, but so are bugs. Target the hotspots you can prove, not every line. Unsafe unchecked math or unbounded loops are not worth a tiny discount.
Design lens Choose clarity unless you can show measurable savings. Keep safety patterns (CEI, reentrancy guards) intact. Measure before and after.
Trade-offs Packing and unchecked blocks can backfire if misunderstood by future maintainers. Leave breadcrumbs (comments/tests) so the intent survives refactors.
Risk management Only optimize code that runs often or costs a lot. Don’t jeopardize simplicity for a few gas when readability prevents mistakes.
Effective gas price (EIP-1559)
effective = min(maxFeePerGas, baseFee + priorityFee)
Total cost = gasUsed × effective. Measure changes against this, not just raw gasUsed.
Key points
- Data locations:Prefer calldata for external inputs; minimize storage reads/writes; cache storage in memory when reused.
- Packing/ordering:Pack smaller types into a single slot; order reads/writes to minimize SLOAD/SSTORE; beware of misaligned types.
- Unchecked:Only when bounds are proven; accompany with tests/invariants; document assumptions.
- Loops:Cache array length, avoid repeated storage loads, consider batching, short-circuit early; avoid unbounded loops on user input.
- External calls:Do not drop safety (checks-effects-interactions, reentrancy guards) for gas; avoid inline assembly unless justified.
- Tooling:Gas snapshots (Forge), hardhat-gas-reporter; compare before/after; remove “optimizations” that harm clarity without benefit.