β Master Gas Optimization
Understand storage packing, code patterns, and advanced techniques
Write efficient smart contracts that save money
Your Progress
0 / 5 completedπ Module Summary
β‘ What You Learned
1. Gas Cost Fundamentals
Storage (SSTORE) costs 20,000 gas vs 3 gas for memory. Understanding this 6,600x difference is the foundation of all optimization. Every technique aims to reduce storage operations.
2. Storage Optimization
Pack variables (uint128+uint64+uint64 = 1 slot, 66% savings), cache storage reads in memory, choose mappings vs arrays strategically. Uniswap, Aave, OpenSea all obsess over storage layout.
3. Code-Level Techniques
Loop optimization (cache length, ++i, unchecked), short-circuiting (cheap checks first), unchecked math (when overflow impossible), inline modifiers. These micro-optimizations compound to 30-50% savings.
4. Advanced Patterns
Assembly (50-70% savings but high risk), calldata (20-40% for arrays), bitmaps (90%+ for boolean flags), minimal proxies (99% for contract clones). Production-grade optimization from elite protocols.
5. Profiling & Measurement
Hardhat gas reporter, Foundry snapshots, Tenderly debugger. Measure before optimizing. 90% of gas in 10% of codeβprofile to find hot spots.
π‘ Key Insights
- β’Storage is 6,600x more expensive than memory. Every optimization technique ultimately aims to reduce storage operations (SSTORE, SLOAD).
- β’Small optimizations compound. 5 gas here, 100 gas thereβacross thousands of transactions, saves millions in aggregate fees.
- β’Profile before optimizing. 90% of gas typically in 10% of code. Measure to find hot spots, optimize those first.
- β’Security trumps gas savings. Don't sacrifice safety for 100 gas. Exploits cost infinitely more than gas fees.
- β’Real-world impact is massive. Uniswap V3's optimizations saved users $50M+. OpenSea Seaport reduced NFT trade costs by 35%.
π― Optimization Priority List
- 1.Pack storage variables: Biggest wins. Group uint128, uint64, uint32. 50-66% reduction.
- 2.Cache storage reads: Read once into memory, operate on memory. Especially in loops.
- 3.Optimize loops: Cache length, ++i, unchecked. 30-50% per loop.
- 4.Use calldata for arrays: Read-only parameters. 20-40% savings.
- 5.Consider bitmaps: For boolean flags. 90%+ savings at scale.
- 6.Assembly for hot paths: Only after profiling. 50-70% but high risk.
π― Knowledge Check
Test your understanding of gas optimization with this 5-question quiz. Each question includes detailed explanations.