Gas Optimization Techniques for Smart Contracts
September 28, 20257 min read
Practical tips and techniques to reduce gas costs in your Solidity smart contracts.
Gas Optimization Techniques for Smart Contracts
Gas optimization is crucial for user experience and cost efficiency. Here are practical techniques to reduce gas consumption in your Solidity contracts.
Storage Optimization
Pack Structs Efficiently
Solidity storage slots are 32 bytes. Pack related variables together:
// Bad: Uses 3 storage slots
struct User {
uint128 balance; // Slot 1
uint64 id; // Slot 2 (wastes space)
bool active; // Slot 3 (wastes space)
}
// Good: Uses 1 storage slot
struct User {
uint128 balance; // Slot 1
uint64 id; // Slot 1
bool active; // Slot 1
}Use uint256 or uint8 Appropriately
- Storage: Use smaller types (uint8, uint128) when you can pack them
- Memory/Stack: Use uint256 (native word size, no conversion needed)
Loop Optimization
Cache Array Length
// Bad
for (uint i = 0; i < items.length; i++) {
// ...
}
// Good
uint length = items.length;
for (uint i = 0; i < length; i++) {
// ...
}Use Unchecked Arithmetic
For loops where overflow is impossible:
for (uint i = 0; i < length; ) {
// ... operations
unchecked { ++i; }
}Function Optimization
Short-Circuit Evaluation
Order conditions by probability:
// Most likely to fail first
require(isValid && amount > 0 && user.active);Use Events Instead of Storage
Events are much cheaper than storage for historical data:
// Good: Use events for historical tracking
event Transfer(address indexed from, address indexed to, uint256 value);Memory vs Storage
- Use memory for temporary variables
- Use calldata for read-only external function parameters
- Avoid copying storage to memory unnecessarily
Best Practices
1. Minimize external calls 2. Batch operations when possible 3. Use libraries for reusable code 4. Consider using proxy patterns for upgradeability
Conclusion
Gas optimization requires balancing readability, security, and cost. Always measure gas usage before and after optimization to verify improvements.