Gas Optimization — Write Efficient Solidity
Save 50%+ on gas costs. Learn the techniques that separate amateur from professional Solidity code.
Gas isn't just a tech detail — it's user experience. A single inefficient loop can make your dApp unusable during high network activity. Optimized contracts = happy users = more adoption.
Top 5 Gas Optimization Techniques
Variable Packing
Pack multiple variables into one 32-byte storage slot. Saves 20,000 gas per slot avoided.
Unchecked Math
Use unchecked {} for safe arithmetic to skip overflow checks. Saves ~20 gas per operation.
Calldata Instead of Memory
For external functions, use calldata for arrays/strings. Avoids copying, saves ~200 gas.
Custom Errors
Replace require strings with custom errors. Saves ~50 gas per revert.
Short-Circuit Conditions
Order && and || conditions by gas cost. Cheapest checks first save wasted computation.
Example: Variable Packing Optimization
❌ Unoptimized (3 slots)
contract Unoptimized {
uint256 timestamp; // Slot 0
address owner; // Slot 1
bool isActive; // Slot 2
// 3 SSTORE operations
// ~60,000 gas on deploy
}✅ Optimized (1 slot)
contract Optimized {
uint64 timestamp; // Slot 0 (8 bytes)
address owner; // Slot 0 (20 bytes)
bool isActive; // Slot 0 (1 byte)
// 1 SSTORE operation
// ~40,000 gas on deploy
}The optimization: Pack uint64, address, and bool into one 32-byte slot (8 + 20 + 1 = 29 bytes). Saves 20,000 gas.
Frequently Asked Questions
Why is gas optimization important?
Gas costs money. A poorly optimized contract can cost users 2-3x more per transaction. For high-volume DeFi protocols, this means millions in wasted fees. Optimization is competitive advantage.
What is the easiest way to save gas?
Use custom errors instead of require strings (saves ~50 gas per revert), pack storage variables tightly (saves 20,000 gas per slot), and use calldata instead of memory for external function parameters (saves ~200 gas per array).
Should I optimize from the start?
No. First make it work, then make it right, then make it fast. Premature optimization leads to bugs. Use Foundry gas snapshots to measure before optimizing.
Master Gas Optimization
Practice 15+ optimization techniques with real code challenges. Measure your improvements with Foundry gas reports.
Start Optimizing →