Gas Calculation & Optimization
Gas calculation in Ethereum involves summing intrinsic costs (21,000 base + calldata encoding), execution costs (per-opcode charges with cold/warm access distinctions), and memory expansion costs — with optimization techniques that can reduce contract gas usage by 30-80%.
Every transaction starts with 21,000 gas intrinsic cost plus calldata encoding (4 gas/zero byte, 16 gas/non-zero byte). During execution, each opcode charges gas: arithmetic ops cost 3-10 gas, memory operations cost 3+ gas, but storage operations dominate — SLOAD costs 2,100 gas (cold) and SSTORE costs up to 22,100 gas (cold, zero-to-nonzero). The Berlin upgrade introduced cold/warm access: first access to a storage slot or address in a transaction is "cold" (expensive I/O), subsequent accesses are "warm" (cached). Gas optimization strategies include storage packing (fitting multiple variables into one 32-byte slot), using events over storage for write-only data, unchecked arithmetic where overflow is impossible, and calldata over memory for read-only function parameters.
Tradeoffs
Strengths
- Detailed understanding of gas costs enables significant cost reductions (30-80%)
- Cold/warm access model accurately reflects underlying hardware I/O costs
- Gas profiling tools provide precise optimization targets
- Storage packing and bitmap patterns offer order-of-magnitude improvements
Weaknesses
- Optimization often sacrifices code readability and maintainability
- Assembly optimizations bypass safety checks, increasing vulnerability risk
- Gas cost schedule changes with hard forks can invalidate optimizations
- Over-optimization can make code harder to audit and verify
Likely Follow-Up Questions
- How does the cold/warm access pattern affect gas optimization strategies?
- What is the SSTORE gas refund and when does it apply?
- How would you design a gas-efficient whitelist for 10,000 addresses?
- Explain the tradeoff between on-chain computation and calldata size on L2.
- When is inline assembly worth the readability tradeoff?
- How does ERC-721A achieve cheaper batch minting?
Source: editorial — Synthesized from EIP-2929, EIP-2200, Foundry documentation, and Solidity optimizer guides