Gas Optimization: What Actually Matters
The 80/20 of gas optimization. Storage packing, calldata vs memory, the SSTORE rules, custom errors, caching reads, the optimizer settings — with real benchmarks.
35 min · expert · part of Solidity & Smart Contract Development
What you'll learn
- The Optimization Mindset
- Storage: The 80% of Optimization
- Calldata, Memory, and Arrays
- Custom Errors, External over Public, Modifier vs Internal
- The Solc Optimizer and via_ir
- Anti-patterns: Optimizations That Don't Help (or Hurt)
Key terms
- Storage Packing
- Declaring consecutive small state variables (uint128, uint64, address, bool, etc.) so they share a single 256-bit storage slot. The single biggest gas-optimization lever in most contracts.
- Cold vs Warm SLOAD
- First read of a storage slot in a transaction costs 2,100 gas (cold). Subsequent reads cost 100 gas (warm). Caching repeated reads in a local variable saves ~2,000 gas per redundant read.
- SSTORE Refund
- Writing zero to a previously non-zero slot refunds up to 4,800 gas (capped at 20% of total transaction gas after EIP-3529). Useful for cleanup operations like closing positions.
- optimizer_runs
- Solc setting that tunes the bytecode-size vs. per-call-gas trade-off. Higher values produce more inlining and cheaper calls but larger bytecode. 200 is balanced; AMMs use 1,000,000+; one-shot deployers use 1.
- via_ir
- Solc's newer optimization pipeline (Yul-based intermediate representation). Generally produces cheaper bytecode at the cost of much slower compilation. Used in production builds, often disabled during development.
- Custom Error (re: gas)
- Defined with the `error` keyword (0.8.4+). Saves ~50 gas per revert vs. `require` with a string, plus reduces bytecode size. Strict win.
- unchecked { }
- Solidity block that disables overflow / underflow checks for the contained arithmetic. Saves ~20-30 gas per operation. Use only in code paths where you can prove overflow is impossible (e.g. for-loop counters with known bounds).
Read the full lesson in the CryptoBipto app.
Open lessonEducational only — not financial advice.
