Gas Optimization in Solidity: Write Efficient Smart Contracts
In Ethereum, every computation costs real money (measured in gas). Optimizing your smart contracts isn’t just about speed—it’s about survival. Let’s explore practical strategies to reduce gas costs.
Why Gas Optimization Matters
- π° Save users money on transactions
- ⛓️ Prevent out-of-gas errors
- π Reduce blockchain bloat
Gas Cost Cheat Sheet
Operation | Gas Cost | Optimized Alternative |
---|---|---|
Storage Write | ~20,000 gas | Memory (100 gas) |
Dynamic Array | High | Fixed-size Array |
Loops | O(n) | Mappings |
Top Optimization Strategies
1. Minimize Storage Operations
// Bad: Multiple storage writes
function update() public {
user.balance += 10;
user.lastUpdate = block.timestamp;
}
// Good: Use memory struct
function update() public {
User memory temp = user;
temp.balance += 10;
temp.lastUpdate = block.timestamp;
user = temp; // Single storage write
}
2. Use Packed Variables
// Wastes space
uint128 a;
uint256 b; // New slot
// Packed (same slot)
uint128 a;
uint128 b;
3. Short-Circuit Conditionals
// Cheap operation first
if (user.isActive && balance > 100) { ... }
4. Batch Operations
// Bad: Looping
for(uint i; i < users.length; i++) { ... }
// Better: Single transaction
function bulkProcess(address[] calldata users) { ... }
⚠️ Costly Patterns to Avoid
- Unbounded loops
- Excessive event emissions
- String manipulation
- Delegatecall in loops
Advanced Techniques
- π ️ Use assembly for critical paths
- π¦ Leverage SSTORE2/SLOAD2 for storage patterns
- π― Bit-packing with bitwise operators
Gas-Saving Checklist
- ✅ Use
calldata
instead ofmemory
for external functions - ✅ Prefer
external
overpublic
when possible - ✅ Cache array length in loops
- ✅ Use
unchecked
blocks for safe math
Your Challenge
Optimize this function:
function sumArray(uint[] memory arr) public pure returns(uint) {
uint total;
for(uint i=0; i<arr.length; i++) {
total += arr[i];
}
return total;
}
Hint: 3 potential optimizations exist!
Comments
Post a Comment