Chapter 8

Gas Optimization

Every EVM opcode costs gas, and users pay for your design choices at transaction time. Optimization is not premature when deploy costs reach thousands of dollars and high-frequency functions price out smaller holders.

Pack smaller uint types into single 256-bit storage slots — two uint128 values share one slot and halve write costs for paired fields. Use calldata for read-only external array parameters instead of copying to memory.

unchecked blocks skip overflow checks where you have already validated bounds — useful in tight loops but dangerous if assumptions change. Profile first, optimize hot paths second, and never sacrifice clarity or safety for marginal savings on cold code paths.