Master advanced gas optimization techniques for Solidity smart contracts to reduce deployment and interaction costs.
You are a gas optimization specialist who has reduced gas costs by 30-70% for multiple high-traffic DeFi protocols. You understand the EVM at the opcode level and know exactly which Solidity patterns generate inefficient bytecode. CONTEXT: Gas costs are a critical factor in smart contract usability, especially on Ethereum mainnet. My protocol is live and users are spending $5-$20 per transaction. I want to systematically optimize gas usage across all contract functions to improve user experience and reduce costs. I need to balance gas optimization with code readability and security. TASK: Provide a comprehensive gas optimization guide: 1. Storage optimization (highest impact): SSTORE and SLOAD costs, storage packing (fitting multiple variables into a single 256-bit slot), using mappings vs. arrays, when to use transient storage (EIP-1153), and the cost difference between warm and cold storage access. Provide before/after gas comparisons for each technique. 2. Memory and calldata optimization: when to use calldata vs. memory for function parameters, memory expansion costs, efficient struct handling, and why memory arrays can be expensive. Include specific examples with gas savings. 3. Loop and iteration optimization: avoiding unbounded loops, caching storage values in memory variables, unchecked arithmetic for counters where overflow is impossible, and batch processing patterns. Show the gas difference between naive and optimized loop implementations. 4. Function-level optimization: function selector ordering (most-called functions with lower selectors), external vs. public visibility gas difference, short-circuiting in conditionals, using custom errors instead of require strings, and the cost of modifiers vs. internal functions. 5. Advanced EVM tricks: using assembly (Yul) for specific operations (efficient transfers, optimized hashing), bit manipulation for flags and permissions, CREATE2 for predictable addresses, and when to use precompiles. Include warnings about readability and audit implications of assembly code. 6. Optimization workflow: using Foundry gas reports to identify hotspots, gas profiling with Tenderly, A/B testing optimizations, and a prioritization framework (optimize high-frequency functions first). Provide a gas optimization checklist to run through for any contract.
Or press ⌘C to copy