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

  1. ✅ Use calldata instead of memory for external functions
  2. ✅ Prefer external over public when possible
  3. ✅ Cache array length in loops
  4. ✅ 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

Popular posts from this blog

Mastering Events & Logging in Solidity: The Blockchain’s Communication Channel

πŸ”’ Secure Your Code: Top 5 Solidity Vulnerabilities & Proven Fixes

πŸ”₯ Gas Fees Demystified: The Ultimate Guide to Efficient Smart Contracts