How do you optimize gas usage in Solidity?

Answer

Gas optimization reduces deployment and transaction costs. Key techniques: (1) Use appropriate variable typesuint256 is most gas-efficient (EVM uses 256-bit words); smaller types like uint8 require additional conversion operations; (2) Storage slot packing — struct members smaller than 32 bytes share a single storage slot if consecutive: struct Packed { uint128 a; uint128 b; } uses 1 slot vs. uint256 a; uint256 b (2 slots); (3) Memory vs. storage — cache storage reads in memory for functions that read the same variable multiple times: uint256 cached = storageVar; return cached + cached * 2; (4) Minimize storage writes — most expensive operation. Use events for data that doesn't need on-chain access; (5) Short-circuit evaluation — put cheaper conditions first in require statements; (6) Use custom errors over stringserror Unauthorized() + revert Unauthorized() is cheaper than require(false, "Unauthorized"); (7) Avoid loops over dynamic arrays — unbounded loops can hit block gas limit; (8) Use mappings over arrays for lookups — O(1) vs. O(n); (9) immutable and constant — mark variables that never change to avoid storage access; (10) Optimizer settings — enable Solidity optimizer with high runs value (200 for deployment cost optimization, 1000+ for call cost).