Previous Module
Transaction Debugging

🏆 Advanced Techniques: Bitwise & Assembly

Discover expert-level gas optimization with Yul assembly

Write efficient smart contracts that save money

🔬 Advanced Gas Techniques

Elite gas optimization requires advanced techniques. Inline assembly gives direct EVM opcode access—Uniswap V3's sqrt calculation uses assembly for 50% gas reduction, but one mistake loses user funds (no safety checks). Calldata optimization—using calldata instead of memory for read-only parameters—saves 1,000+ gas by avoiding memory copies. Bitmaps pack 256 boolean flags into one storage slot (90%+ savings)—Uniswap's token airdrop used bitmaps to track claims for 10M+ users. Minimal proxies (EIP-1167) deploy 200-byte clones instead of full contracts (99% cheaper)—Gnosis Safe creates wallet instances this way. These techniques separate amateur from expert optimization.

🎮 Interactive: Advanced Technique Explorer

Select a technique to see code examples, gas savings, real-world usage, and safety considerations.

⚙️

Inline Assembly

50-70% savingsHigh Risk

Direct EVM opcodes bypass Solidity safety checks

💻 Code Example
// Save 200+ gas per call
function getBalance(address user) returns (uint) {
  // Solidity: ~500 gas
  return balances[user];
  
  // Assembly: ~300 gas
  assembly {
    mstore(0x00, user)
    mstore(0x20, balances.slot)
    let hash := keccak256(0x00, 0x40)
    let value := sload(hash)
    mstore(0x00, value)
    return(0x00, 0x20)
  }
}
🏭 Production Use Cases

Uniswap V3 uses assembly for sqrt math (50% gas reduction). OpenSea Seaport uses assembly for order validation.

⚠️ Safety Considerations

No overflow checks, no type safety. One mistake = funds lost. Only use for hot paths after extensive testing.

🛠️ Gas Profiling Tools

Hardhat Gas Reporter: Automatic gas reporting for tests. npx hardhat test --gas-reporter shows function costs in table format.
Foundry Gas Snapshots: forge snapshot creates baseline. forge snapshot --diff shows before/after changes. Commit snapshots to git.
Tenderly Debugger: Visual transaction traces with gas costs per opcode. See exactly which line costs the most.
eth-gas-reporter: CI integration, tracks gas over time, alerts on regressions. Essential for production contracts.

📊 Optimization Checklist

💡 When NOT to Optimize

  • Security over gas: Don't sacrifice safety for 100 gas. Exploits cost infinitely more.
  • Readability matters: Complex optimizations need extensive comments. Future you will thank you.
  • Measure first: Profile to find hot spots. 90% of gas in 10% of code. Optimize that 10%.
  • L2s change math: On Arbitrum/Optimism, calldata is expensive. Optimization priorities differ.